How to get the index of the element in javascript?

后端 未结 5 742
北海茫月
北海茫月 2021-02-07 15:09

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

5条回答
  •  青春惊慌失措
    2021-02-07 15:24

    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.

提交回复
热议问题