doggie brezy
doggie brezy

Reputation: 297

Get the child node index of an element having the caret position to its contenteditable parent element

Now I have asked this question before and it was marked as duplicate to this question Get caret position in contenteditable div including tags But infact it is totally different.

Lets say I have a contenteditable div which also has some element in it

<div id="text" contenteditable="true"><b>abc</b><nav>def</nav><span>ghi</span></div>

Now if the cursor or caret position is within the span element, how do I get the index of the span element as a child node to its parent element div. So I can have this result

divNode = document.querySelector('div');
caretEle = //get the caret position element which will be span
spanIndex = //probably divNode.indexOf(caretEle) which will be = 2
caretEle = divNode.childNodes[spanIndex];

NOTE: I am not looking for the caret position, I want to get the child index of the caret position element to its parent element. ie I want to get the child index of the <span> element to the <div id="text" contenteditable="true">

For example:

node = document.getElementById('text');
node.childNodes[0] == <b>
node.childNodes[1] == <nav>
node.childNodes[2] == <span>

Upvotes: 1

Views: 1525

Answers (1)

John
John

Reputation: 13719

var s = window.getSelection();
var an = s.anchorNode;
var fn = s.focusNode;

The anchorNode represents the textNode where selection begins while the focusNode is where the selection ends; presuming that the elements contain a textNode otherwise the browser might return the element itself. It's very important to remember that the anchorNode is where the user initially started the selection, so if they selected from right-to-left, the anchorNode will be on the right side whereas if they selected the text from left-to-right the anchorNode will be on the left side.

Upvotes: 1

Related Questions