SEE BEFORE MARKING DUPLICATE/DOWNVOTING
- The contenteditable div will not have child elements
- I do not want to set the position at the end of the div
- I do not want a cross-browser solution, only Chrome support required
- Only vanilla JS, no libraries.
I have seen many many solutions. Many by Tim Down, and others. But none does work. I have seen window.getSelection
, .addRange
etc. but don't see how they apply here.
Here's a jsfiddle.
(Tried) Code:
var node = document.querySelector("div");
node.focus();
var caret = 10; // insert caret after the 10th character say
var range = document.createRange();
range.setStart(node, caret);
range.setEnd(node, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);