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

180
Views
Set range to select text accross multiple child nodes

I have some issue to set range to select text within a div.

Here is a fiddle I use for the test.

I succeed do it within first child only using node.firstChild:

  let selection = window.getSelection();
  var node = document.getElementById("textZone");
  var textZone = node.firstChild;
  selection.removeAllRanges();
  range = document.createRange();
  range.setStart(textZone, 0);
  range.setEnd(textZone, 2);
  selection.addRange(range);

But where I only use node (as per the fiddle), the value of setStart and setEnd will defined the child number of the node instead of the position value of the first and last letter position.

My goal is to be able to proceed selection accross the entire text based on caracter position value. For example, selection should be:

  • middle of node child 2 to middle of node child 4

The result to achieve is, when I press the button, I get that selection : enter image description here

Please let me know if you have any ideas.

Thank you

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

0

I am not sure what exactly you want to achieve but your approach will not work like this. If you want just to extract the plain text than just do range.toString(); and apply some string functions to get your result.

The problem with document.createRange() is the fact that it works with nodes and what you really want is just a part of a node. Imagine that your node is the parent for others like: <strong>ins<i>is</i>t</strong> .... You will have somehow to split the node and create new nodes with the remaining parts and another nod with the wanted part. So your <strong>insist</strong> should look like

<strong>ins</strong><strong>ist</strong>
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!