JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value="place caret" onclick="setCaret('editableDiv1', 'span1');">
<div id="editableDiv1" contenteditable="true" spellcheck="false">This one <span id="span1">is</span> working.</div>
<input type="button" value="place caret" onclick="setCaret('editableDiv2', 'span2');">
<div id="editableDiv2" contenteditable="true" spellcheck="false">This one <span id="span2"></span> is not.</div>
CSS
body {
padding: 10px;
font-family: sans-serif;
}
input {
margin-bottom: 10px;
padding: 5px;
}
input:last-of-type {
margin-top: 50px;
}
div {
width: 300px;
padding: 5px;
border: solid 1px #000;
}
span {
font-weight: bold;
}
JavaScript
function setCaret(x, y) {
var element = document.getElementById(x);
var range = document.createRange();
var node;
node = document.getElementById(y);
range.setStart(node.childNodes[0], 0);
var sel = window.getSelection();
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
element.focus();
}