How to get the index of the element in javascript?

The NodeList objet is an Array-like object. So it's possible to "convert" it into an Array using Array.prototype.slice.call()

var arr = Array.prototype.slice.call(yourNodeListObject); // Now it's an Array.
arr.indexOf(element); // The index of your element :)

On browsers that support ES6 you can also do this with Array.from()

const arr = Array.from(yourNodeListObject);

or using the spread operator ...

const arr = [...yourNodeListObject];

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

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

Tags:

Javascript