问题
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