tonymx227 tonymx227 - 17 days ago 5
Javascript Question

Set caret position in a content editable element

I'd like to set caret position in a content editable element but it seem's not working.



var el = document.getElementsByTagName('div')[0];
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el, 2);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();

<div contenteditable>Hi ! How are you doing ?</div>




Answer

Try this:
Just replace range.setStart(el, 2) with range.setStart(el.childNodes[0], 2)

var el = document.getElementsByTagName('div')[0];
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[0], 2);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
<div contenteditable>Hi ! How are you doing ?</div>

You are passing the wrong node to the setStart function. Need to pass a text node.

Comments