Cannot read property 'querySelectorAll' of Undefined in JS

avatar

Borislav Hadzhiev

Last updated: Oct 21, 2021

banner

Photo from Unsplash

Cannot read property 'querySelectorAll' of Undefined #

The "Cannot read property 'querySelectorAll' of undefined" error occurs for 2 reasons:

  1. Calling the querySelectorAll() method on an undefined value (DOM element that doesn't exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

cannot read property queryselectorall of undefined

Here is an example of how the error occurs.

index.js
const el = undefined; // ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'querySelectorAll') el.querySelectorAll('div.box');

To solve the "Cannot read property 'querySelectorAll' of undefined" error, make sure you're using the correct class name to access th DOM element. The error often occurs after providing an invalid class name to the getElementsByClassName method.

index.js
const elements = document.getElementsByClassName('does-not-exist'); console.log(elements); // 👉️ [] // ⛔️ Cannot read properties of undefined (reading 'querySelectorAll') const boxes = elements[0].querySelectorAll('div.box');

We passed a non-existent class name to the getElementsByClassName() method and got an empty array-like object back.

Accessing an array at an index out of bounds returns undefined. Calling the querySelectorAll() method on an undefined value throws the error.

To solve the "Cannot read property 'querySelectorAll' of undefined" error, place the JS script tag at the bottom of the body tag. The script should run after the DOM elements have been created.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="container"> <div class="box">Box 1</div> <div class="box">Box 2</div> </div> <!-- ✅ GOOD - div elements are already created ✅ --> <script src="index.js"></script> </body> </html>

Notice that we placed the JS script tag at the bottom of the body tag.

Had we placed the script tag above the div element, the index.js file wouldn't have access to the div elements.

index.js
const elements = document.getElementsByClassName('container'); console.log(elements); // 👉️ [div.container] // ✅ Works const boxes = elements[0].querySelectorAll('div.box'); console.log(boxes); // 👉️ [div.box, div.box]

Conclusion #

The "Cannot read property 'querySelectorAll' of undefined" error occurs when trying to call the querySelectorAll method on an undefined value.

To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.