Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How to get which word is selected in span

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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); 

about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!