Last active
November 14, 2017 11:23
-
-
Save moqmar/9e4a1e0727b1a1da10ce9423d83821b6 to your computer and use it in GitHub Desktop.
Select all text in an element
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
// Modified version of https://stackoverflow.com/a/987376 | |
function selectText(el) { | |
if (!el) return; | |
var range, selection; | |
if (document.body.createTextRange) { | |
range = document.body.createTextRange(); | |
range.moveToElementText(el); | |
range.select(); | |
} else if (window.getSelection) { | |
selection = window.getSelection(); | |
range = document.createRange(); | |
range.selectNodeContents(el); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
} | |
} | |
document.addEventListener("click", function(event) { | |
selectText( | |
event.target.P | |
? event.target.P(".select-on-click") | |
: event.target.classList.contains("select-on-click") | |
? event.target | |
: null); | |
}); |
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
function selectText(el){if(!el)return;var range,selection | |
if(document.body.createTextRange){range=document.body.createTextRange();range.moveToElementText(el);range.select()}else | |
if(window.getSelection){selection=window.getSelection();range=document.createRange();range.selectNodeContents(el);selection.removeAllRanges();selection.addRange(range)}} | |
document.addEventListener("click",function(event){selectText(event.target.P?event.target.P(".select-on-click"):event.target.classList.contains("select-on-click")?event.target:null)}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment