Last updated: Mar 3, 2024
Reading timeยท2 min
The "Cannot read properties of null (reading 'setAttribute')" error occurs for 2 reasons:
setAttribute()
method on a DOM element that doesn't exist.Here is an example of how the error occurs.
const el = document.getElementById('does-not-exist'); console.log(el); // ๐๏ธ null // โ๏ธ Uncaught TypeError: Cannot read properties of null (reading 'setAttribute') el.setAttribute('style', 'color: green');
We attempted to call the setAttribute
method on a null
value which caused
the error.
setAttribute
Make sure the id
you use to get the DOM element is valid.
The error often occurs when calling the getElementById
method with an invalid
id
.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ `id` should match with JS code --> <div id="box"></div> <script src="index.js"></script> </body> </html>
The id
set on the element in your HTML code should match the id
you pass in
the call to the document.getElementById()
method.
Make sure to place the JS script tag at the bottom of the body tag, after the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ BAD - script is run before div is created โ --> <script src="index.js"></script> <div id="box"></div> </body> </html>
Notice that the JS script tag is placed above the div
element.
Therefore the index.js
file is run before the HTML element is created, so you
can't access the div
inside the index.js
file.
const el = document.getElementById('box'); console.log(el); // ๐๏ธ null // โ๏ธ Cannot read properties of null (reading 'setAttribute') el.setAttribute('style', 'color: green');
You should insert the JS script tag at the bottom of the body, after the DOM elements are created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <h2>bobbyhadz.com</h2> <!-- โ GOOD - div is already created โ --> <script src="index.js"></script> </body> </html>
Now the div
element will be accessible inside of the index.js
file.
const el = document.getElementById('box'); console.log(el); // ๐๏ธ div#box // โ works el.setAttribute('style', 'color: green');
HTML code is parsed from top to bottom, so the script tag has to be placed at the bottom of the body tag, after all of the DOM elements it needs to access.
The "Cannot read properties of null (reading 'setAttribute')" error occurs when
trying to call the setAttribute
method on a null
value.
To solve the error, make sure you're providing the correct id
to the
getElementById
method and load the JS script after the DOM elements are
created.