How to fix querySelectorAll is not a function error in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError:querySelectorAll is not a function error in JavaScript.
The TypeError: “TypeError:querySelectorAll is not a function” error occurs one of the following reasons:
-
Using the querySelectorAll on a invalid dom object or HTML element.
-
Calling JS file before the HTML declaration.
-
Calling a querySelectorAll method with incorrect name.
Let’s see a example of how the error occurs and how to fix it:
<div class="row">Data 1</div>
<div class="row">
<div class="column">Column 1</div>
<div class="column">Column 2</div>
</div>
<div class="row">Data 3</div>
Now, we need to access the three divs inside the JavaScript using the document.querySelectorAll()
method.
const elements = document.querySelectorAll(".row");
console.log(elements); // [div.row, div.row, div.row]
const el = elements.querySelectorAll(".column")
// it gives error elements.querySelectorAll is not a function
console.log(el);
it gives a error elements.querySelectorAll is not a function, because we are using the querySelectorAll
on a NodeList, but it is only available on document object.
To fix the “querySelectorAll is not a function” error, makesure call the querySelectorAll() method on a valid dom object or HTML element and place your JavaScript file after the body tag.
Here is example:
<div class="row">Data 1</div>
<div class="row">
<div class="column">Column 1</div>
<div class="column">Column 2</div>
</div>
<div class="row">Data 3</div>
const elements = document.querySelectorAll(".row .column");
console.log(elements);
Output:
HTMLCollection(3) [div.column, div.column]
It returns a html collection of two divs.
We can also loop through the divs
by first converting the HTML collection into array and we can loop it using the forEach() method.
const elements = document.querySelectorAll(".row .column");
[...elements].forEach(el => console.log(el));
In the example above, we first converted the HTML collection to array using the spread operator then we used the forEach method to loop through the each element.
Conclusion
To fix the “querySelectorAll is not a function” error, makesure call the querySelectorAll() method on a valid dom object or HTML element and place your JavaScript file after the body tag.