Zenoo Zenoo - 2 years ago 106
HTML Question

Contenteditable set carret on a child node

I'm having some difficulties while trying to set the carret after an

<i>
tag inside a
contenteditable
.

Here is what I have :

<p contenteditable="true"><i>H</i><i>e</i><i>l</i><i>l</i><i>o</i></p>


How do I put the carret after the .. let's say 3rd
<i>
tag here?

I already tried this solution :

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


But I don't know how to make it work with the position of the
<i>
tags instead of the chars.

Answer Source

var el = document.getElementsByTagName('p')[0];
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[3], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
<p contenteditable="true"><i>H</i><i>e</i><i>l</i><i>l</i><i>o</i></p>

In p 5 child nodes are there, if you want to set caret at child node use range.setStart(el.childNodes[3], 0);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download