“TypeError: Cannot Read Property ‘setAttribute’ Of Null” In JavaScript

"TypeError: Cannot read property 'setAttribute' of Null" in JavaScript

If you don’t know how to fix “TypeError: Cannot read property ‘setAttribute’ of Null” in JavaScript, let’s read this article now. Read from the beginning to the end of this article to find out what causes the error and solutions.

When does the “TypeError: Cannot read property ‘setAttribute’ of Null” in JavaScript happen?

This error occurs for two reasons. First, we call the setAttributed method on DOM (Document Object Model) that doesn’t exist. Second, give the JS script tag before the DOM elements that are declared in HTML.

So, check out the code below to look at the error and how we can correct the issue.

Example 1:

idx.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div id="learn"></div>

    <script src="idx.js"></script>
  </body>
</html>

idx.js

const er = document.getElementById('DOM does not exist');
console.log(er); 

er.setAttribute('style', 'color: red');

Output:

null
"error""TypeError: Cannot read properties of null (reading 'setAttribute')
    at qilenajeri.js:4:4"

Example 2: Here is a code example by HTML, which creates an error “cannot read property of null”.

idx.html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset = "UTF-8" />
</head>

<body>

 <script src = "idx.js"></script>

 <button id = "button" onclick="console.log('Button is clicked')">
 Check
 </button>

</body>

</html>

And here is idx.js:

const learn = document.getElementById("learnshare"); 
console.log(learn);
learn.click();

Output:

null
"error"
"TypeError: Cannot read properties of null (reading 'click') at null.js:4:3"

Now, why don’t we look at the solution to fix this error?

Solutions to fix this error

Moving your JS script tag to the bottom of the body tag

As we know, we get this error because we give the JS script tag before the DOM elements that are declared in HTML. So we just need to move your JS script tag to the bottom of the body tag. Follow the example below.

idx.html

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8" />
</head>

<body>

 <button id="button" onclick="console.log('Button is clicked')"> //DOM element created Check
 </button>

 <script src="idx.js"></script> //JS tag at the end of body tag

</body>

</html>

idx.js

const learn = document.getElementById("button"); 
console.log(learn);
learn.click()

Output:

Summary

That’s what this article is all about. Hope you find the best solution to fix the “TypeError: Cannot read property ‘setAttribute’ of Null” in JavaScript. If you have any questions, please leave a comment below. I will answer as possible. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *