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 for 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.
Hello HTML page

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 the code tries to set the property innerText of null, which is not possible as there is no such property on a null object.

But why does the document.getElementById(“welcome”) return null, and not an HTML element in the first place. There is an HTML element with that ID, right?

This happens because the script tries to access that HTML element before it appears on the page.

But why is that?

You have probably placed the JavaScript 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.

In this case, let’s move the script 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!

Scroll to Top