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?
Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With