cpburnz cpburnz - 1 year ago 201
Javascript Question

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?


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;

Is there a better way to determine the child's index? (in either Firefox or Chrome)

Liv Liv
Answer Source

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 ) 
//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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download