Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  158] [ 6]  / answers: 1 / hits: 46969  / 14 Years ago, thu, september 23, 2010, 12:00:00

The NodeList don't have a indexOf(element) method? So, how can I get the element index?


More From » javascript

 Answers
30

By iterating over the elements, and checking if it matches.



Generic code that finds the index of the element within it's parents childNodes collection.



function index(el) {
var children = el.parentNode.childNodes,
i = 0;
for (; i < children.length; i++) {
if (children[i] == el) {
return i;
}
}
return -1;
}


Usage:



// should return 4
var idx = index(document.body.childNodes[4]);


EDIT: I can't delete an accepted answer, but @kennebec's answer below is much better, which I'll quote verbatim:




You can use Array.prototype.indexOf.call() like this



let nodes = document.getElementsByTagName('*');
Array.prototype.indexOf.call(nodes, document.body);


[#95525] Tuesday, September 21, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anayaashleyh

Total Points: 597
Total Questions: 96
Total Answers: 86

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
;