indexOf() function not working on arrays

百般思念 提交于 2020-01-07 02:52:18

问题


I have two divs as shown below:

<div class="container"></div>
<div class="container"></div>

I created an array using these two divs:

var containers = document.querySelectorAll(".container");

I also created a variable to represent the first div:

var div1 = document.querySelectorAll(".container")[0];

When I use indexOf() to get the index of the first div in the array, I get an error:

containers.indexOf is not a function

Here is a snippet summarizing my problem:

var containers = document.querySelectorAll(".container");
var div1 = document.querySelectorAll(".container")[0];
containers.indexOf(div1); // returns the error
<div class="container"></div>
<div class="container"></div>

回答1:


querySelectorAll returns a NodeList, not an array. You can convert the NodeList to an array by calling Array.from(...).




回答2:


Queryselectorall returns non-live node list. The indexOf method is not defined on that. More info is here

https://developer.mozilla.org/en-US/docs/Web/API/NodeList

You could use Array.from() to convert to array and then use indexOf



来源:https://stackoverflow.com/questions/44960845/indexof-function-not-working-on-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!