Javascript selected text highlighting prob
document.getElementById('execute').addEventListener('click', function() { var range = window.getSelection().getRangeAt(0), span = document.createElement('span'); span.className = 'highlight'; span.appendChild(range.extractContents()); range.insertNode(span);});
.highlight { background-color: yellow; }
<div id="test"> Select any part of <b>this text and</b> then click 'Run'.</div><button id="execute">Run</button>
Rather than reinvent the wheel, I'd use Rangy's highlighting capabilities.
I've forked the fiddle that RGraham created and created a new fiddle that shows how it works. This is how it is done:
var applier = rangy.createClassApplier("highlight");var highlighter = rangy.createHighlighter();highlighter.addClassApplier(applier);document.getElementById('execute').addEventListener('click', function() { highlighter.removeAllHighlights(); highlighter.highlightSelection("highlight");});
What this does is create a highlighter that will set the highlight
class on elements that are wholly inside the selection, and create spans with the highlight
class as needed for elements that straddle the selection. When the button with the id execute
is clicked, the old highlights are removed and the new highlights applied.
The highlighter functionality is part of release of Rangy that are considered to be "alpha". However, I've been consistently using alpha releases of Rangy for a few years now but it has been extremely rare that I found a problem with my application that I could trace back to Rangy. And the few times I found a problem with Rangy, Tim Down (its author) was quite responsive.
try this:
newNode.appendChild(range.extractContents())
according to MDN:
Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.
Whereas Range.surroundContents:
An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.
Didn't test, but...