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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read property 'classList' of Null #

There are 2 reasons the "Cannot read property 'classList' of null" error occurs:

  1. Accessing the classList property on a null value - a DOM element that doesn't exist.
  2. Placing the JS script tag above the HTML, where the DOM elements are declared.
index.js
const box = document.getElementById('does-not-exist'); console.log(box); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot read properties of null (reading 'classList') box.classList.add('bg-green-400');

To solve the "Cannot read property 'classList' of null" error, make sure the id you're using to get the DOM element is valid and exists in the DOM. The error often occurs when providing an invalid id to the getElementById method.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ๐Ÿ‘‡๏ธ id should match with JS code --> <div id="box">Hello</div> <script src="index.js"></script> </body> </html>

To solve the "Cannot read property 'classList' of null" error, place the JS script tag at the bottom of the body tag. The JS script tag should be executed after the HTML elements are declared.

index.html
<!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 id="box">Hello</div> </body> </html>

The index.js script is ran before the HTML elements have been created, therefore you can't access the HTML elements in the index.js file.

index.js
const box = document.getElementById('box'); console.log(box); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot read properties of null (reading 'classList') box.classList.add('bg-green-400');

Instead, you should place the script tag after the DOM elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Hello</div> <!-- โœ… GOOD - div already exists โœ…๏ธ --> <script src="index.js"></script> </body> </html>

Now the div with id of box is accessible inside the index.js file.

index.js
const box = document.getElementById('box'); console.log(box); // ๐Ÿ‘‰๏ธ div#box // โœ… works box.classList.add('bg-green-400');

Conclusion #

The "Cannot read property 'classList' of null" error occurs when trying to access the classList property on a null value.

To solve the error, make sure the JS script tag is loaded after the HTML is created and the id of the element exists in the DOM.

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