Cannot read property 'querySelectorAll' of Undefined in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Frank Park

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.
index.js
const el = undefined; // โ›”๏ธ 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee