Wais Kamal
Wais Kamal

Reputation: 6210

indexOf() function not working on arrays

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>

Upvotes: 2

Views: 945

Answers (2)

Pratik Gaikwad
Pratik Gaikwad

Reputation: 1568

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

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817128

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

Upvotes: 6

Related Questions