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

352
Views
On selecting text from HTML paragraph using window.getSelection(), the range index value is giving 0 when text from different/child tag is selected

I am trying select text from a HTML paragraph and get the index range.

To get the range values, i'm using the below code

{
startIndex = window.getSelection().getRangeAt(0).startOffset;
endIndex = window.getSelection().getRangeAt(0).endOffset;
}

Below is the HTML paragraph.

<p>Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

Now when i select the word "habitant" the startOffset() is returning 0 as a new/child tag started but i need the index starting from the paragraph

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

0

It returns 0 because the work "habitant" is wrapped inside another node so the anchor node won't be the hall paragraph it'll be just the node <b>haitant</b> you can either fix this by removing the tag <b>.

<p class="text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

another workaround will be to search for the selected word inside the parent node

<p class="text">Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>



const getSelectedTextIndex = () => {
    const selectedText = window.getSelection().toString()
    startIndex = document.querySelector('.text').innerText.indexOf(selectedText)
    endIndex = startIndex + selectedText.length
}
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!