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>...
document.querySelector("#container").addEventListener("input", function() {
this.innerHTML = "<span>" + this.innerText
.replaceAll("&", "&") //escape HTML
.replaceAll("<", "<")
.replaceAll(">", ">")
.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.
I want to use the input event because I want it to split while the person is typing, and not when they click out.