Reputation: 11786
How to get the position of an Element in the childNode list?
e.g.
<a>
<b></b><!-- return 0 -->
<c></c><!-- return 1 -->
</a>
Upvotes: 0
Views: 2363
Reputation: 122404
I don't think there's a straightforward way other than to repeatedly call getPreviousSibling()
until it returns null or iterate through the parent node's child list until you find one that is ==
to the node you started with.
As an aside, in the document you give in the question the b
element is index 1 in its parent's list of children, and the c
element is index 3, because there are whitespace-only text nodes in between (one between the opening a
and opening b
and another between the closing b
and opening c
).
Upvotes: 0
Reputation: 1075159
I don't think Element
, Node
, or NodeList
provide a direct way to get this info, but it's easy enough to write your own quick function to do it:
int indexOfNode(Node node) {
int index;
Node sibling;
index = 0;
while ((sibling = node.getPreviousSibling()) != null) {
node = sibling;
++index;
}
return index;
}
Upvotes: 4