获取子节点索引 [英] Get child node index
问题描述
直截了当的javascript(即没有扩展,如jQuery等),是否有一种方法来确定父节点内的子节点的索引,而不迭代和比较所有的子节点?
In straight up javascript (i.e., no extensions such as jQuery, etc.), is there a way to determine a child node's index inside of its parent node without iterating over and comparing all children nodes?
例如,
var child = document.getElementById('my_element');
var parent = child.parentNode;
var children = parent.children;
var count = children.length;
var child_index;
for (var i = 0; i < count; ++i) {
if (child === children[i]) {
child_index = i;
break;
}
}
有没有更好的方法来确定孩子的索引?
Is there a better way to determine the child's index?
推荐答案
您可以使用 previousSibling
属性重复通过兄弟姐妹直到你收到 null
并计算你遇到的兄弟姐妹数量:
you can use the previousSibling
property to iterate back through the siblings until you get back null
and count how many siblings you've encountered:
var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.
请注意,在Java语言中,有一个 getPreviousSibling() / code>函数,但是在JS中,这已经成为一个属性 -
previousSibling
。
Please note that in languages like Java, there is a getPreviousSibling()
function, however in JS this has become a property -- previousSibling
.
这篇关于获取子节点索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!