我想找到具有id的子div的索引'whereami'.
<div id="parent">
<div></div>
<div></div>
<div id="whereami"></div>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
目前我正在使用此函数来查找子项的索引.
function findRow(node){
var i=1;
while(node.previousSibling){
node = node.previousSibling;
if(node.nodeType === 1){
i++;
}
}
return i; //Returns 3
}
var node = document.getElementById('whereami'); //div node to find
var index = findRow(node);
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/grantk/F7JpH/2/
问题
当有数千个div节点时,while循环必须遍历每个div来计算它们.这可能需要一段时间.
有没有更快的方法来解决这个问题?
*请注意,id将更改为不同的div节点,因此需要能够重新计算.
通常我这样做:
for(i=0;i<elem.parentNode.length;i++) {
if (elem.parentNode[i] == elem) //.... etc.. etc...
}
Run Code Online (Sandbox Code Playgroud)