How to find a React DOM node that represents its actual html element?

Here is my problem if you are interested: I want to find the text selected by the user and insert the tag at the beginning and at the end of this selection (select the text).

The best approach to finding selection that is cited by the main minds of StackOverflow is to use window.getSelection() .

This, combined with getRangeAt(0) , displays a list of things where startContainer and endContainer look particularly promising. startContainer.parentNode points directly to the p tag. I started the selection. Great!

However, how do I really know which element it represents in the React DOM? How can I manipulate correctly?

+5
source share
2 answers
 window.addEventListener("mousedown", function(e){console.log(e)}); 

using this event listener (or it is better to use mouseup), you can find all the data about the target, for example: if you copy / paste this piece of code into the console and see the log, you will find all the information about this event includes the target, timestamp, switch key, control key, x, y, that mouse button and all relevant information. if you combine this with what you described earlier, you will get the desired results

0
source

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.

0
source

Source: https://habr.com/ru/post/1275627/


All Articles