Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Joakim Honkasalo
The "Cannot read property 'querySelector' of null" error occurs for 2 reasons:
querySelector()
method on a null
value (DOM element that
doesn't exist).Here is an example of how the error occurs.
const element = null; // ❌ Cannot read properties of null (reading 'querySelector') const box = element.querySelector('#box');
To solve the "Cannot read property 'querySelector' of null" error, make sure
you're using the correct id
when getting the DOM element. The error often
occurs after providing an invalid id
to the getElementById
method.
const element = document.getElementById('does-not-exist'); console.log(element); // 👉️ null // ❌ Cannot read properties of null (reading 'querySelector') const box = element.querySelector('#box');
We provided a non-existent id
to the getElementById
method, so we got a
null
value back. Calling the querySelector()
method on a null
value causes
the error.
To solve the "Cannot read property 'querySelector' of null" error, place the JS script tag at the bottom of the body tag. The JS script should run after the DOM elements are created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before div exists ⛔️ --> <script src="index.js"></script> <div id="container"> <div id="box">Text</div> </div> </body> </html>
The JS script tag is placed above the DOM elements it tries to access, therefore
the div
element will not be accessible inside the index.js
file.
const element = document.getElementById('container'); console.log(element); // 👉️ null // ❌ Cannot read properties of null (reading 'querySelector') const box = element.querySelector('#box');
Instead, place the JS script tag at the bottom of the body, after the DOM elements it tries to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="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 element = document.getElementById('container'); console.log(element); // 👉️ div#container // ✅ Works const box = element.querySelector('#box'); console.log(box); // 👉️ div#box
The "Cannot read property 'querySelector' of null" error occurs when trying to
call the querySelector()
method on a null
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.