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 <p>
, <b>
, <em>
etc... elements.
To highlight the range of text I am wrapping the range in a span element.
The issue:
https://jsfiddle.net/7fedkobr/1/
Here is a sentence with some HTML markup:
<p>The <b>quick</b> brown fox jumps over the <em>lazy</em> dog</p>
When I select a word such as 'The' it gets wrapped in a <span>
, boom, no problem.
The issues come when I try and select over any html tags... for example if I select the entire sentence then I lose ALL my mark-up.
What I am looking for.
A method to serialize the spans so that they fall in-between the html elements and wrap all the text.
Using the previous example: if I select the entire sentence above then I would get the following output:
<p><span>The </span><b><span>quick</span></b><span> brown fox jumps over the </span><em><span>lazy</span></em><span> dog</span></p>
Q:
Is there a method for this kind of serialization? I can't find anything in the jQuery docs and the few people I have asked were stumped.