Borislav Hadzhiev
Mon Mar 28 2022·2 min read
Photo by Luke Porter
The "Cannot set property 'className' of null" error occurs for 2 reasons:
className
property on a null value (DOM element that doesn't
exist).Here's an example of how the error occurs.
const el = null; // ⛔️ Cannot set properties of null (setting 'className') el.className = 'bg-coral';
To resolve the "Cannot set property 'className' of null" error, make sure that
the DOM element you're setting the className
property on exists. The error
most commonly occurs if you use the getElementById()
method and pass it an
id
that is not present in the DOM.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Error: Cannot set properties of null (setting 'className') el.className = 'bg-coral';
In the example, an element with the provided id
does not exist in the DOM, so
the getElementById
method returns a null
value. When we try to set the
className
property on a null
value, the error occurs.
To solve the "Cannot set property 'className' of null" error, make sure that the JS script tag is placed at the bottom of the body, after the HTML elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-coral { background-color: coral; } </style> </head> <body> <!-- ⛔️ BAD - script is ran before div exists ⛔️ --> <script src="index.js"></script> <div id="box">Hello world</div> </body> </html>
The JS script tag is added above the code that declared the div
element. The
index.js
file is ran before the div
element is created, therefore we can't
access the div
from the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ null // ⛔️ Error: Cannot set properties of null (setting 'className') el.className = 'bg-coral';
Instead, the JS script tag has to be moved below the DOM elements that it tries to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .bg-coral { background-color: coral; } </style> </head> <body> <div id="box">Hello world</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now, the div
element can be accessed from the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ null // ✅ Works el.className = 'bg-coral';
Now that the HTML element is created before the index.js
script is ran, we are
able to access the DOM element and set its className
property.
The "Cannot set property 'className' of null" error occurs when:
className
property on a null
value (a DOM element that
doesn't exist)