Last active
August 29, 2015 14:01
-
-
Save kentliau/2fbc9124a50c254cad9e to your computer and use it in GitHub Desktop.
Select text with Vanilla and jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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