Reputation: 7055
I want to set cursor/caret position manually. This is working fine if contents are only text in a contenteditable
. But if content contains text with bold, underline etc then the it is not working and it throws and error
Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 2.
in below sample if you enter "0" in Node number then the cursor moves. But if you enter "1" in Node number then it throws error. What's wrong in it to move cursor over bold text.
button.onclick = () => {
let range = new Range();
range.setStart(p.childNodes[node.value], start.value);
document.getSelection().removeAllRanges();
document.getSelection().addRange(range);
};
<p id="p" contenteditable="true">This is <b>bold</b></p>
Cursor Position <input id="start" type="number" value="2"> Node number <input id="node" type="number" value="0">
<button id="button">Mover Cursor</button>
Upvotes: 0
Views: 241
Reputation: 613
In your example, p.childNodes[1]
resolves to the node <b>bold</b>
. You can only jump to the start or end of its text (index 0 and 1), as you are viewing the node as a whole. If you want to set the cursor within this node, you have to access its actual textual contents.
While not working for more complex cases, this should push you in the right direction:
let childNode = p.childNodes[node.value];
while (childNode.hasChildNodes()) {
childNode = childNode.firstChild;
}
range.setStart(childNode, start.value);
Upvotes: 1