Skip to content Skip to sidebar Skip to footer

Serializing Html: Placing Span Elements Around Selected Text While Preserving The HTML Structure

I am trying to make a text highlighter where a teacher can select a range of text so that the student can follow along. The text is formatted with HTML so there are

, <

Solution 1:

The key is to use range.extractContents(). The documentation states the most important part for your needs:

Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.

document.getElementById('test').addEventListener('mouseup', 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 sentence and</b> and then move the mouse to a new location.
</div>

You can see in the picture below that the resulting HTML from a selection does exactly what you are asking:

DOM representation of selection.


Solution 2:

I don't think you need jquery for that, plain CSS will do the trick:

*::selection { background-color: yellow !important; }

Post a Comment for "Serializing Html: Placing Span Elements Around Selected Text While Preserving The HTML Structure"