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

146
Vistas
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 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