Get child node index
ES—Shorter
[...element.parentNode.children].indexOf(element);
The spread Operator is a shortcut for that
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.
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.