EDIT: As Mox indirectly mentioned ... When React re-renders, all new nodes will be overwritten and the selection will be lost. This option, like it, will not work well with React.
I am going to leave this answer here because it is an option if the selected text is not re-displayed frequently.
I believe that the [surroundContents][1] method will be very useful to you.
According to the documentation you can create a new node. Set the class attribute to this new node. This class should include the highlight you want.
You can then pass the new node to the surroundContents method to place the content selected by the range into the 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 that you already have a range object, so you just need to create a new node to wrap the selected text and use the surroundContents method.
I see one serious problem with this method.
If the user selects text from inside the container and outside the same container, a situation may arise, such as the following:
<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 a problem for you.
Tyler source share