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 thislet nodes = document.getElementsByTagName('*'); Array.prototype.indexOf.call(nodes, document.body);