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 http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Surrounding for more details).
Is there any good way to split this range into 2 ranges and embolden both halfs separately to get around this problem?
function makeBold() {
var selection = window.getSelection();
if (selection.rangeCount) {
var range = selection.getRangeAt(0).cloneRange();
var newNode = document.createElement("b");
range.surroundContents(newNode);
selection.removeAllRanges();
selection.addRange(range);
}
}
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: