Highlight Selected Text On A Page When Spanning Multiple Non Text Nodes
I'm trying to write some code which will highlight any text selected on a page, the following code works in most cases but not when the range partially selects a non-text node (see
Solution 1:
You could use document.execCommand()
. Note that in non-IE browsers you'll have to temporarily make the document editable.
jsFiddle: http://jsfiddle.net/C7j5H/1/
Code:
function highlight() {
var range, sel;
// IE case
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.execCommand("Bold", false, null);
} else if (window.getSelection) {
// Non-IE
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand("Bold", false, null);
document.designMode = "off";
}
}
Post a Comment for "Highlight Selected Text On A Page When Spanning Multiple Non Text Nodes"