Uncaught TypeError: cannot set property ‘innerHTML’ of null

Commonly you see the Uncaught TypeError: cannot set property innerText of null error if you try to access an HTML element on a page before it appears.

The solution. Move your JavaScript from the head to the body tag below the HTML element you are trying to access.

An Example Situation

Let’s say you are asking user input to display a greeting on a front page.

This is how your HTML/JavaScript code might look like in an index.html file

<html>  
  <head> 
    <script type = "text/javascript">
      var nickname = prompt("Please enter your name: ");

      if (nickname != null) {
        document.getElementById("welcome").innerText =
          "Hello, " + nickname + "!";
      }
    </script> 
  </head>  

  <body>  
    <h1 id="welcome"> Hello! </h1>  
  </body>
</html>  

If you open the index.html file, the page shows a prompt that asks a user for their name:

But when you enter the name, you are only going to see a bare “Hello!” without the name you just entered.

If you now open up the console, you can see there is an error:

Uncaught TypeError: Cannot set properties of null (setting 'innerText')

This error says it is trying to set the property innerText of null, which is obviously not possible. There is no such property on a null object. But why does the document.getElementById(“welcome”) return null, and not a HTML element? There is an HTML element with that ID, right?

The reason why this happens is that the script tries to access that HTML element before it appears on the page. This in turn happens because you have placed the script in the head tag of your HTML document.

To run the script after the element has appeared on the page, you need to place the script after that element in the HTML. So let’s move the script part below the h1 tag:

<html>  
  <head>   
  </head>  

  <body>  
    <h1 id="welcome"> Hello! </h1>  
  </body>
  
  <script type = "text/javascript">
    var nickname = prompt("Please enter your name: ");

    if (nickname != null) {
      document.getElementById("welcome").innerText =
      "Hello, " + nickname + "!";
    }
  </script> 
</html>

If you now open up the index.html with your browser, you can see that the greeting works!

Conclusion

Today you learned why you sometimes see the ‘cannot set property of null’ error in HTML/JavaScript.

To recap, this error occurs commonly when you try to modify an HTML element that has not appeared yet on the page. The solution is to move your JavaScript code from the head tag below the HTML element.

Thanks for reading.

Happy coding!

Further Reading

100 JavaScript Interview Questions

50+ Web Development Buzzwords

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.