Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Caleb Fisher
The "Cannot read property 'className' of null" error occurs for 2 reasons:
className
property on a null
value - a DOM element that
doesn't exist.Here is an example of how the error occurs.
const el = null; // ⛔️ Cannot read properties of null (reading 'className') const clsName = el.className;
To solve the "Cannot read property 'className' of null" error, make sure
you're using the correct id
when getting the DOM element. The error often
occurs when an invalid id
is provided to the getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'className') console.log(el.className);
We passed an id
that doesn't exist to the getElementById
method, so we got a
null
value back. Accessing the className
property on a null
value causes
the error.
The id
should match between your js
and html
code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- 👇️ id is `box` --> <div id="box" class="text-blue-400">Hello World</div> <script src="index.js"></script> </body> </html>
To solve the "Cannot read property 'className' of null" error, place the JS script tag at the bottom of the body tag. The script should be ran after the DOM elements are created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before div is created ⛔️ --> <script src="index.js"></script> <div id="box" class="text-blue-400">Hello World</div> </body> </html>
The JS script is ran before the DOM element is created. This means that the
div
element will not be accessible in the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'className') console.log(el.className);
Instead, you should place the script at the bottom of the body tag, after the DOM elements that the script tries to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" class="text-blue-400">Hello World</div> <!-- ✅ GOOD - div is already created ✅ --> <script src="index.js"></script> </body> </html>
Now the div
element is accessible inside of the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ div#box console.log(el.className); // 👉️ "text-blue-400"
The "Cannot read property 'className' of null" error occurs when accessing the
classList
property on a variable that stores a null
value.
To solve the error, make sure to only access the classList
property on valid
DOM elements.