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

155
Views
How can I put individual words in <span> elements in a contenteditable <div>?

question

How do I put words in <span> elements in a contenteditable <div> while still keeping the cursor position? For example: if someone typed:
"the fox guy jumped over the dog", it would output:

<span>the</span> <span>fox</span> <span>guy</span>... 

attempt

document.querySelector("#container").addEventListener("input", function() {
    this.innerHTML = "<span>" + this.innerText
        .replaceAll("&", "&amp;") //escape HTML
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;")
        .split(" ")
        .join("</span><span>") + "</span>";
});

It didn't work because it didn't keep the cursor position, it just teleported the cursor to the end.

UPDATE:

I want to use the input event because I want it to split while the person is typing, and not when they click out.

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!