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 better way to determine the child's index?
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.