小编典典

JavaScript DOM:在容器中查找元素索引

html

我需要通过对象引用在其容器内找到元素的索引。奇怪的是,我找不到简单的方法。请不要jQuery-只有DOM。

UL
 LI
 LI
 LI - my index is 2
 LI

是的,我可以为每个元素分配ID并遍历所有节点以匹配ID,但这似乎是一个不好的解决方案。没有更好的东西吗?

因此,就像上面的示例一样,我有一个对第三个LI的对象引用。我怎么知道它是索引2?

谢谢。


阅读 647

收藏
2020-05-10

共1个答案

小编典典

您可以使用Array.prototype.indexOf。为此,我们需要在某种程度上“铸成” HTMLNodeCollectiontrue
Array。例如:

var nodes = Array.prototype.slice.call( document.getElementById('list').children );

然后我们可以调用:

nodes.indexOf( liNodeReference );

例:

var nodes = Array.prototype.slice.call( document.getElementById('list').children ),

    liRef = document.getElementsByClassName('match')[0];



console.log( nodes.indexOf( liRef ) );


<ul id="list">

    <li>foo</li>

    <li class="match">bar</li>

    <li>baz</li>

</ul>
2020-05-10