JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://www.timdown.co.uk/rangy/rangy-1.1.2/uncompressed/rangy-core.js"></script>
<div id="text" contentEditable="true">hi this is <input type="button" class="token" value="[Your Name]" disabled="disabled" />, can you help me? :)</div>
<button id="go" unselectable="on">go</button>
CSS
div, button
{
margin: 20px;
}
JavaScript
function setCaretCharIndex(containerEl, index) {
var charIndex = 0, stop = {};
function traverseNodes(node) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (index >= charIndex && index <= nextCharIndex) {
rangy.getSelection().collapse(node, index - charIndex);
throw stop;
}
charIndex = nextCharIndex;
}
// Count an empty element as a single character. The list below may not be exhaustive.
else if (node.nodeType == 1
&& /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) {
charIndex += 1;
} else {
var child = node.firstChild;
while (child) {
traverseNodes(child);
child = child.nextSibling;
}
}
}
try {
traverseNodes(containerEl);
} catch (ex) {
if (ex != stop) {
throw ex;
}
}
}
rangy.init();
$("#go").click(function() {
setCaretCharIndex($("#text")[0], 15);
$("#text").focus();
return false;
});