EDIT:
As Mox had indirectly mentioned... When React re-renders, all the of the new nodes would be over-written and the highlighting would be lost.
This option as it is won't work well with React.
I'm going to leave this answer here since it is an option if the highlighted text is not being re-rendered often.
I believe the [surroundContents][1]
method will be of great use to you.
According to the documentation, you can create a new node. Setup the class attribute on that new node. This class should enable the highlighting you want.
Then you can pass the new node into the surroundContents
method to place the content selected by the range into your new node.
Here is an example from the documentation:
var range = document.createRange();
var newNode = document.createElement("p");
range.selectNode(document.getElementsByTagName("div").item(0));
range.surroundContents(newNode);
I believe you already have a range object, so you would just need to create a new node to wrap the highlighted text and use the surroundContents
method.
I do see 1 major concern with this method.
If a user highlights text from inside a container and outside the same container, a situation like following may occur:
<p>
some text
<span class="highlighting">
some more text
</p>
some other text
</span>
I do not know how surroundContents
will handle this, so this may be become a problem for you.