Get child node 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 ofelement
, including that element.Array.from
→ Casts the constructor ofchildren
to anArray
objectindexOf
→ You can applyindexOf
because you now have anArray
object.