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