I would like to apply a style, such as a yellow background, to the text that a user selects on my webpage. Unfortunately, the selected text may cross node boundaries (e.g. it may begin in the middle of one div and end in the middle of another div).
What is the best way to wrap a span (or multiple spans) around all of the selected text?
Set up
<div>This sentence is not selected. THIS SENTENCE </div>
<div>IS SELECTED. This sentence is not selected.</div>
Desired result
<div>This sentence is not selected. <span>THIS SENTENCE</span> </div>
<div> <span>IS SELECTED.</span> This sentence is not selected.</div>
Here are two similar questions (one, two) restricted to the case when the selection does not cross node boundaries.