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

143
Views
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
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!