Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child node index

Tags:

javascript

dom

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?

like image 980
Uyghur Lives Matter Avatar asked May 06 '11 15:05

Uyghur Lives Matter


People also ask

What is a child node in JavaScript?

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.


1 Answers

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); 
like image 77
KhalilRavanna Avatar answered Oct 12 '22 20:10

KhalilRavanna