I've been working on a real-time HTML highlighter that surrounds selected text with span elements containing a background property.
Check out the fiddle here: https://jsfiddle.net/4hd2vrex/
The issue arises when users make multiple selections, leading to nested spans and messy content like this:
<span style="background-color: rgb(255, 255, 131);">
r
<span style="background-color: rgb(255, 255, 131);">
<span style="background-color: rgb(255, 255, 131);">
e
</span>
p
</span>
r
<span style="background-color: rgb(255, 255, 131);">
e
</span>
h
<span style="background-color: rgb(255, 255, 131);">
end
</span>
e
<span style="background-color: rgb(255, 255, 131);">
rit
</span>
</span>
To address this mess, I came up with the following solution:
Instead of adding more spans, just replace all the selected text - including any existing span tags - with the original selection using window.getSelection()
.
For instance, if I were to select the jumble of spans above, I would first replace them with window.getSelection()
, which is simply the text reprehenderit, resulting in:
<span style="background-color: rgb(255, 255, 131);">reprehenderit</span>
Q: How can I swap my selection for the selected text?