Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Frank Park
The "Cannot read property 'querySelectorAll' of undefined" error occurs for 2 reasons:
querySelectorAll()
method on an undefined
value (DOM element
that doesn't exist).Here is an example of how the error occurs.
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.
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.
<!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.
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]
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.