Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Joakim Honkasalo
The "Cannot read property 'querySelector' of undefined" error occurs for 2 reasons:
querySelector()
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 'querySelector') const box = el.querySelector('#box');
To solve the "Cannot read property 'querySelector' of undefined" error, make
sure you're calling the method on a valid DOM element. The error often occurs
after passing an invalid class name to the getElementsByClassName
method.
const elements = document.getElementsByClassName('does-not-exist'); console.log(elements); // 👉️ [] // ⛔️ Cannot read properties of undefined (reading 'querySelector') const box = elements[0].querySelector('#box');
We passed a non-existent class name to the getElementsByClassName
method, so
we got an empty array-like object back.
Trying to access an array at an index out of bounds, returns an undefined
value and calling the querySelector
method on an undefined
value causes the
method.
To solve the "Cannot read property 'querySelector' of undefined" error, insert 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> <!-- ⛔️ BAD - script runs before div is created ⛔️ --> <script src="index.js"></script> <div class="container"> <div id="box">Text</div> </div> </body> </html>
We placed the JS script tag above the code that declares the DOM elements. This
means that the div
element won't be accessible inside the index.js
file.
const elements = document.getElementsByClassName('container'); console.log(elements); // 👉️ [] // ⛔️ Cannot read properties of undefined (reading 'querySelector') const box = elements[0].querySelector('#box');
Instead, place the JS script tag at the bottom of the body tag, after the DOM elements it needs access to.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="container"> <div id="box">Text</div> </div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now we can access the div
element inside of the index.js
file.
const elements = document.getElementsByClassName('container'); console.log(elements); // 👉️ [div.container] // ✅ Works const box = elements[0].querySelector('#box'); console.log(box); // 👉️ div#box
The "Cannot read property 'querySelector' of undefined" error occurs when trying
to call the querySelector
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.