Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
childNodeリスト内の要素の位置を取得するにはどうすればよいですか?
例えば
<a> <b></b><!-- return 0 --> <c></c><!-- return 1 --> </a>
Element、、Nodeまたはこの情報を取得する直接的な方法を提供するとは思いませんが、NodeListそれを行うための独自のクイック関数を作成するのは簡単です。
Element
Node
NodeList
int indexOfNode(Node node) { int index; Node sibling; index = 0; while ((sibling = node.getPreviousSibling()) != null) { node = sibling; ++index; } return index; }
getPreviousSibling()nullが返されるまで繰り返し呼び出すか、最初のノードにあるものが見つかるまで親ノードの子リストを反復処理する以外に、簡単な方法はないと思います==。
getPreviousSibling()
==
余談ですが、質問で指定したドキュメントでは、b要素は親の子リストのインデックス1であり、c要素はインデックス3です。これは、間に空白のみのテキストノードがあるためです(1つは開始aと開始の間b、もう1つはクローズbとオープニングの間c)。
b
c
a