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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read Property 'setAttribute' of Null #

The "Cannot read Property 'setAttribute' of null" error occurs for 2 reasons:

  1. Calling the setAttribute() method on a DOM element that doesn't exist.
  2. Inserting the JS script tag above the HTML, where the DOM elements are declared.
index.js
const el = document.getElementById('does-not-exist'); console.log(el); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot read properties of null (reading 'setAttribute') el.setAttribute('style', 'color: green');

To solve the "Cannot read property 'setAttribute' of null" error, 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.

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

To solve the "Cannot read property 'setAttribute' of null" error, make sure to place the JS script tag at the bottom of the body tag, after the DOM elements have been declared.

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

Notice that the JS script tag is placed before the div element.

This means that the index.js file is executed before the HTML element is created, therefore you can't access the div inside the js file.

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

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <!-- โœ… 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.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ div#box // โœ… works el.setAttribute('style', 'color: green');

Conclusion #

The "Cannot read property 'setAttribute' of null" 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.

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