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
The NodeList don't have a indexOf(element) method? So, how can I get the element index?
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);