I have the following scenario:
contents are displayed in div.
Users can select words from that content.
I am fetching selection of the user using window.getselection().tostring() method.
Now I want the location of the selected contents inside span/div.
For eg. Parent div has contents like this:
<span>abc xyz abc</span>
<div>abc xyz abc</div>
<span>abc xyz abc</span>
So if I select 1st abc from 1st span or I select 2nd abc in 1st span or I select abc abc from 1st span and second div then what will be the best way to highlight the selected part.
Thanks in advance
How below solution can be useful
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute("style", "background-color: pink;");
range.surroundContents(newNode);
it works for me very well :
import React, {useEffect, useRef} from 'react';
const App = () => {
const spanInput=useRef();
useEffect(()=>{
console.log(spanInput.current.innerHTML)
},[spanInput])
return (
<div>
<span ref={spanInput}>test text</span>
</div>
);
};
export default App;