Solve - Cannot read property 'querySelector' of Null in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Solve - Cannot read property 'querySelector' of Null #

The "Cannot read property 'querySelector' of null" error occurs for 2 reasons:

  1. Calling the querySelector() method on a null value (DOM element that doesn't exist).
  2. Inserting the JS script tag above the HTML where the DOM elements are declared.
index.js
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.

index.js
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.

index.html
<!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.

index.js
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.

index.html
<!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.

index.js
const element = document.getElementById('container'); console.log(element); // ๐Ÿ‘‰๏ธ div#container // โœ… Works const box = element.querySelector('#box'); console.log(box); // ๐Ÿ‘‰๏ธ div#box

Conclusion #

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.

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