Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created February 17, 2014 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/9050248 to your computer and use it in GitHub Desktop.
Save barneycarroll/9050248 to your computer and use it in GitHub Desktop.
Selects the text of the scoped element.
// Selects the text of the scoped element.
// Courtesy of @jcubic: http://stackoverflow.com/a/21829549/356541
$.fn.sel = function selectText() {
var node = this[0];
if ( document.body.createTextRange ) {
var range = document.body.createTextRange();
range.moveToElementText( node);
range.select();
} else if ( window.getSelection ) {
var selection = window.getSelection();
if (selection.setBaseAndExtent) {
selection.setBaseAndExtent(node, 0, node, 1);
} else {
var range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment