JavaScript DOM:在容器中查找元素索引 [英] JavaScript DOM: Find Element Index In Container

查看:101
本文介绍了JavaScript DOM:在容器中查找元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find an index of element inside its container by object reference. Strangely, I cannot find an easy way. No jQuery please - only DOM.

UL
 LI
 LI
 LI - my index is 2
 LI

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

Yes, I could assign IDs to each element and loop through all nodes to match the ID but it seems a bad solution. Isn't there something nicer?

所以说,我有一个对象引用第三个LI,如上面的例子。如何知道这是索引2?

So, say I have an object reference to the third LI as in the example above. How do I know it is index 2?

谢谢。

推荐答案

您可以使用 Array.prototype.indexOf 。为此,我们需要将HTMLNodeCollection转换成一个真正的数组。例如:

You could make usage of Array.prototype.indexOf. For that, we need to somewhat "cast" the HTMLNodeCollection into a true Array. For instance:

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>

这篇关于JavaScript DOM:在容器中查找元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆