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>
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.
If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.
If it's not textarea it counds the child elements for offsets.
You can set different elements in the contenteditable like this:
<div contenteditable>
<p>para 1</p>
<p>para 2</p>
<p>para 3</p>
<p>para 4</p>
</div>
<script>
var el = document.getElementsByTagName('div')[0];
var p = document.querySelector('p');
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el, 3);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With