How do you highlight text in JavaScript? I tried http://jsfiddle.net/WdeTM/ but it doesn't work.
<span id="foo" >bar</span>
document.getElementById("foo").focus();
How do you highlight text in JavaScript? I tried http://jsfiddle.net/WdeTM/ but it doesn't work.
<span id="foo" >bar</span>
document.getElementById("foo").focus();
Ok, first of all the question should be - How can I select a piece of text using JS?
Highlighting is different from selecting text(Yes, your title is good!)
This should help:
Working demo
function selectText(element) {
var doc = document;
var text = doc.getElementById(element);
if (doc.body.createTextRange) { // ms
var range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { // moz, opera, webkit
var selection = window.getSelection();
var range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
selectText('foo');
Just found the original author for my long saved sniplr snippet, credits : @Jason thread here.