Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda