Skip to content

Instantly share code, notes, and snippets.

@kentliau
Last active August 29, 2015 14:01
Show Gist options
  • Save kentliau/2fbc9124a50c254cad9e to your computer and use it in GitHub Desktop.
Save kentliau/2fbc9124a50c254cad9e to your computer and use it in GitHub Desktop.
Select text with Vanilla and jQuery
// jQuery highlight text plugins
// It will select the text of first occurence
// of jQuery collection of element
jQuery.fn.selectText = function(){
var doc = document
, element = this[0]
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
return selection.toString() || range.toString();
};
// VanillaJS text highlight
// require a DOM element as parameter
function selectText(element) {
var doc = document
, text = element
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
return selection.toString() || range.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment