How to get the index of the element in javascript?

后端 未结 5 730
北海茫月
北海茫月 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:43

    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];
    

提交回复
热议问题