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

140
Visualizações
How do I keep the caret position when I update the innerHTML of the contenteditable div it is in?

I am trying to make some code with a contenteditable div, so if you type some specific words, they change colour. I got this working thanks to some stack overflow (What else) but whenever I update the innerHTML of the element I am working with, it moves my caret (The blinky thing that you type with) To the start of the text. Is there a way I can preserve my caret position in this div?

const words = [
  "apple",
  "banana",
  "pear"
]

document.getElementById("colordiv").addEventListener("keypress", colorchange)

function colorchange() {
  var cont = document.getElementById("colordiv").innerHTML.split(" ");
  for (i = 0; i < cont.length; i++) {
    if (words.includes(cont[i])) {
      cont[i] = "<span style='color:blue'>" + cont[i];
      cont[i] = cont[i] + "</span>";
    }
    document.getElementById("colordiv").innerHTML = cont.join(" ");
  }
}
<div id="colordiv" contenteditable="true">
  This text can be edited by the user.
</div>

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