开发者

Get child node index

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?

E.g.,

var child = document.getElementById('my_element');
var parent = child.parentNode;
var childNodes = parent.childNodes;
var count = childNodes.length;
var child_index;
for (var i = 0; i < count; ++i) {
  if (child === childNodes[i]) {
    child_index = i;
    break;
  }
}

Is there a bet开发者_开发百科ter way to determine the child's index?


I've become fond of using indexOf for this. Because indexOf is on Array.prototype and parent.children is a NodeList, you have to use call(); It's kind of ugly but it's a one liner and uses functions that any javascript dev should be familiar with anyhow.

var child = document.getElementById('my_element');
var parent = child.parentNode;
// The equivalent of parent.children.indexOf(child)
var index = Array.prototype.indexOf.call(parent.children, child);


ES6:

Array.from(element.parentNode.children).indexOf(element)

Explanation :

  • element.parentNode.children → Returns the brothers of element, including that element.

  • Array.from → Casts the constructor of children to an Array object

  • indexOf → You can apply indexOf because you now have an Array object.


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.

Please note that in languages like Java, there is a getPreviousSibling() function, however in JS this has become a property -- previousSibling.

Use previousElementSibling or nextElementSibling to ignore text and comment nodes.


ES—Shorter

[...element.parentNode.children].indexOf(element);

The spread Operator is a shortcut for that


0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜