简体   繁体   中英

org.w3c.dom.Element get position in parent

How to get the position of an Element in the childNode list?

eg

<a>
  <b></b><!-- return 0 -->
  <c></c><!-- return 1 -->
</a>

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;
}

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM