Home > Software design >  How to get which word is selected in span
How to get which word is selected in span

Time:11-14

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

CodePudding user response:

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); 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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;
  • Related