Set caret position at a specific position in contenteditable div
You need to position the caret within the text node inside your element, not the element itself. Assuming your HTML looks something like <div contenteditable="true">Some text</div>
, using the firstChild
property of the element will get the text node.
Updated jsFiddle:
Code:
var node = document.querySelector("div");node.focus();var textNode = node.firstChild;var caret = 10; // insert caret after the 10th character sayvar range = document.createRange();range.setStart(textNode, caret);range.setEnd(textNode, caret);var sel = window.getSelection();sel.removeAllRanges();sel.addRange(range);