This my code but there is an error if you override the highlighted text.
The error is:
Uncaught InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.
JS
function surroundSelection() { var span = document.createElement("span"); span.setAttribute('class', 'hlt') if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount) { var range = sel.getRangeAt(0).cloneRange(); range.surroundContents(span); sel.removeAllRanges(); sel.addRange(range); } } }
surroundContentsitself can't do the job. You have to look at what's in the range and deal with how to highlight the selection cross-element. MDN even flags this up: "An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points." So you'll need more than one span in that case.