3 Simple Ways to Fix “cannot set property ‘innerHTML’ of null” Error

Cannot set property ‘innerHTML’ of null or “Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)” is a very common error when you call JavaScript from the HTML. In this article, you will know the different possible reasons for this error and their possible solutions.

cannot set property 'innerHTML' of null

What is meant by “cannot set property ‘innerHTML’ of null”?

InnerHTML sets or returns the HTML content of the HTML element. It will be executed only on the HTML element.
If the getElementById(“”) does not find the required element for the input id, then it returns a null value and when innerHTML is executed on the null value it throws “cannot set property ‘innerHTML’ of null” error message.

The followings are the possible three scenarios where you may get the “cannot set property ‘innerHTML’ of null” error message.

1. HTML DOM element is not loaded before the JavaScript

All the web browsers load the HTML elements and JavaScript codes written inside the Script tag from top to bottom. If you are trying to access the HTML node element from the script tag, you must make sure that it is already loaded by the browser before executing the script code or it may result in “Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)” error.

Example:

In the following example, content of the HTML element firstElement is called inside the script tag before it is actually loaded by the browser. This is because firstElement is declared after the script tag. The browser first executes the script tag and then the firstElement div tag sequentially which results in an error message.

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Tech Support Whale Document</title>
      <script type ="text/javascript">
         testScript();
         function testScript(){
             document.getElementById('firstElement').innerHTML;
         };
      </script>
   </head>
   <body>
      <div id="firstElement">Welcome to TechSupportWhale !</div>
   </body>
</html>

Solution:

Declare the id firstElement above the script tag. So that browser loads the firstElement before calling the script tag as shown below. The browser executes the javascript code without any error message.

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Tech Support Whale Document</title>
   <body>
      <div id="firstElement">Welcome to TechSupportWhale !</div>
   </body>
   <script type ="text/javascript">
      testScript();
      function testScript(){
          document.getElementById('firstElement').innerHTML;
      };
   </script>
   </head>
</html>

2. Incorrect DOM element ID

There is a possibility you might have mistyped element id passed to the getElementById(“”) function. Double-check if you have the correct element id passed.

   <body>
      <div id="firstElement">Welcome to TechSupportWhale !</div>
   </body>
   <script type ="text/javascript">
      testScript();
      function testScript(){
          document.getElementById('firstElemen').innerHTML;
      };
   </script>

In the above example, the wrong element id is passed to the getElementById function. GetElementById(“”) function fails to read the input element id that causes the error.

3. Access DOM Element using windows.load event

Alternately you can also use windows.onload event which executes when bowser is finished loading all the other DOM elements. So your javascript code will not fail even if you call it before the declaration of the element node as shown below.

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Tech Support Whale Document</title>
      <script type ="text/javascript">
         window.onload = function() {
                        testScript();
                        function testScript(){
                            document.getElementById('firstElement').innerHTML;
                        };
                    }
         		
      </script>
   <body>
      <div id="firstElement">Welcome to TechSupportWhale !</div>
   </body>
   </head>
</html>

In the above example windows.onload function holds execution of testScript() until browser loads the firstElement element node.

Conclusion:

These are the three different solutions to solve “cannot set the property ‘innerHTML’ of null” and I hope the error is resolved now. If you are still facing the issue, do share your HTML code in the comment section or you can reach out to us using the Contact Form, we will try to resolve your query to the best of our knowledge.

2 thoughts on “3 Simple Ways to Fix “cannot set property ‘innerHTML’ of null” Error”

  1. Pig Game

    <!– –>

    Game of PIG
    There are two players. The player whose tuen it is rolls the dice. The totel of the roll is
    added to the current player’s score, unless either die comes up as a “one”. If this
    happensm this player’s turn is over, and it is the otjer players turn. After the current
    player can either roll again, (assuming a ‘one’ was not rolled) or if the current
    player feels that luck is running thin, they can pass to the other player to get 30
    points or higher wins.

    Oh, and if you roll two “ones” (snakes eyes), your current score gets zeroed out.
    so don’t do that.

    Start a Game
    Randomly Pick the First Player, and Start the Game

    apps.js file

    const startGame = document.getElementById(‘startgame’)
    const gameControl = document.getElementById(‘gameControl’)
    const game = document.getElementById(‘game’)
    const score = document.getElementById(‘score’)
    const actionsArea = document.getElementById(‘actions’)
    gameData = {
    // We will use an object here to keep track of data in game.
    // we are adding this object to the script
    dice: [‘dice_1.png’, ‘dic_2.png’, ‘dic_3.png’, ‘dic_4.png’, ‘dic_5.png’, ‘dic_6.png’],

    players: [‘player 1’, ‘player 2’],
    score: [0, 0],
    roll1: 0,
    roll2: 0,
    rollSum: 0,

    index: 0,
    gameEnd: 29
    }

    startGame.addEventListener(‘click’, function() {

    gameData.index = Math.round(Math.random())

    gameControl.innerHTML != ‘ The Game HAS Started ‘
    gameControl.innerHTML += `Do You Wanna Quit?`
    document.getElementById(‘quit’).addEventListener(‘click’, function (){
    location.reload()
    })
    // console.log(gameData.index)
    })

Leave a Comment

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

Scroll to Top
Scroll to Top