Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda