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

223
Views
JavaScript Range setStart not working on "Bold" Text

I want to set cursor/caret position manually. This is working fine if contents are only text in a contenteditable. But if content contains text with bold, underline etc then the it is not working and it throws and error

Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 2.

in below sample if you enter "0" in Node number then the cursor moves. But if you enter "1" in Node number then it throws error. What's wrong in it to move cursor over bold text.

  button.onclick = () => {
    let range = new Range();

    range.setStart(p.childNodes[node.value], start.value);
  
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(range);
  };
<p id="p" contenteditable="true">This is <b>bold</b></p>

Cursor Position <input id="start" type="number" value="2">  Node number <input id="node" type="number" value="0">
<button id="button">Mover Cursor</button>

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

0

In your example, p.childNodes[1] resolves to the node <b>bold</b>. You can only jump to the start or end of its text (index 0 and 1), as you are viewing the node as a whole. If you want to set the cursor within this node, you have to access its actual textual contents.

While not working for more complex cases, this should push you in the right direction:

let childNode = p.childNodes[node.value];
while (childNode.hasChildNodes()) {
  childNode = childNode.firstChild;
}
    
range.setStart(childNode, start.value);
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!