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

265
Views
How to set cursor position in contenteditable div without random span

I have two divs inside a contenteditable div, like this:

<div contenteditable="true" id="mainDiv">
  <div id="div1">Line 1</div>
  <div id="div2">Line 2</div>
</div>

and I want to set the cursor at the beginning of "Line 2". I use the following code to do so

function setCursorAtInnerDiv(mainDiv, div2) {
  let range = document.createRange();
  range.selectNodeContents(div2);
  range.collapse(true);
  let selection = document.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
}

When I look at the elements, the divs look just as shown above all the way until this code returns.

Then suddenly the HTML gets messed up like this:

<div contenteditable="true" id="mainDiv">
  <div id="div1">Line 1</div>
  <span style="font-family: -apple-system...; font-size: 1rem;">Line 2</span>
</div>

(where "..." is a bunch of fonts listed). The end result is that instead of a 'div', I know have a 'span', which means Line 2 does not start on its own line.

Why did my div turn into a span (with a bunch of font stuff in it)? Did Chrome do that? I sure didn't.

How can I set the cursor position without messing up my lines? Is there a "don't ruin my html" flag?

about 4 years ago · Juan Pablo Isaza
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!