I have a html page with text content. On selecting any text and pressing the highlight button, I can change the style of the selected text to highlight the same. To implement th
This solution is bit tricky, but I find it would be sufficient
When you will see closely in selection object that we get through calling
window.getSelection().getRangeAt(0)
You will se that there are 4 properties: startContainer
, startOffset
, endContainer
, endOffset
.
So now you need to start with startContainer
with startOffset
and start putting your necessary span nodes from there.
If now it endContainer
is different node then you need to start traversing nodes from startContainer
to endContainer
For traversing you need to check for child nodes and sibling nodes which you can get from DOM objects. So first go through startContainer
, go through all its child and check if child node is inline element then apply span tag around it, and then you need to write few coding for various corner cases.