How to get the index of the element in javascript?

Viewed 40405

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

5 Answers

Let us say you have the following line:

const list=document.querySelectAll('.some_class .someother_class');

list will be a nodelist. So we can convert the nodelist to an array and create a new array of indexes as follows:

const indexArr= [...list].map( element => return [...list].indexOf(element) );

indexArr contains all the indexes of elements in the original list.

Just add one line in your script:

NodeList.prototype.indexOf = Array.prototype.indexOf;   // for IE11

Then use indexOf as usual:

var index = NodeList.indexOf(NodeElement);
Related