Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set caret position in a content editable element [duplicate]

Tags:

javascript

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>
like image 461
tonymx227 Avatar asked Nov 16 '16 13:11

tonymx227


Video Answer


2 Answers

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.

like image 75
Rakesh G R Avatar answered Oct 20 '22 00:10

Rakesh G R


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>
like image 37
user2693928 Avatar answered Oct 19 '22 23:10

user2693928