Select All Text In Element on Click (JavaScript OR jQuery)
To select all text inside an element such as DIV, we can simply use JavaScript document.createRange() method to create a range, and than using range.selectNodeContents() we can set node range (start and end), after which use selection.addRange() to select the range of the element.JavaScript
This JavaScript code does its primary function which is to select all the text inside an element, but we don't want to annoyingly select everything every-time the element is clicked. We only want user to be able to highlight the portion of the text within the element.JS
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
function selectText(id){
var sel, range;
var el = document.getElementById(id); //get element id
if (window.getSelection && document.createRange) { //Browser compatibility
sel = window.getSelection();
if(sel.toString() == ''){ //no text selection
window.setTimeout(function(){
range = document.createRange(); //range object
range.selectNodeContents(el); //sets Range
sel.removeAllRanges(); //remove all ranges from selection
sel.addRange(range);//add Range to a Selection.
},1);
}
}else if (document.selection) { //older ie
sel = document.selection.createRange();
if(sel.text == ''){ //no text selection
range = document.body.createTextRange();//Creates TextRange object
range.moveToElementText(el);//sets Range
range.select(); //make selection.
}
}
}
HTML
- 1
- 2
- 3
<div onclick="selectText(this.id)" id="elementID">
//Text
</div>
jQuery
If you want to use it as jQuery code, just put the code inside jQuery "mouseup" event method, something like this:JQUERY
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
$("#elementID").on('mouseup', function() {
var sel, range;
var el = $(this)[0];
if (window.getSelection && document.createRange) { //Browser compatibility
sel = window.getSelection();
if(sel.toString() == ''){ //no text selection
window.setTimeout(function(){
range = document.createRange(); //range object
range.selectNodeContents(el); //sets Range
sel.removeAllRanges(); //remove all ranges from selection
sel.addRange(range);//add Range to a Selection.
},1);
}
}else if (document.selection) { //older ie
sel = document.selection.createRange();
if(sel.text == ''){ //no text selection
range = document.body.createTextRange();//Creates TextRange object
range.moveToElementText(el);//sets Range
range.select(); //make selection.
}
}
});
HTML
- 1
- 2
- 3
<textarea id="elementID">
//Some text here
</textarea>