Mar 22, 2015

[SOLVED] Uncaught TypeError: Cannot set property 'innerHTML' of null

This happens when your innerHTML code is trying to insert into a html element/tag that doesn't exist or named differently.

The code below will produce error - the HTML doesn't have an element with the id "result":

HTML -

<body>
<header></header>
  <div id="main">
  </div>
  <footer></footer>

  <script>
     var person = {
         firstName: "John",
         lastName : "Doe",
         id       : 5566,
         fullName : function(c) {
            return 'My name is ' + this.firstName + " " + this.lastName;
         }
     };
     document.getElementById("result").innerHTML = person.fullName ();
  </script>
</body>


This will work:

<body>
<header></header>
<div id="main">
</div>
<footer></footer>

<script>
  var person = {
      firstName: "John",
      lastName : "Doe",
      id       : 5566,
      fullName : function(c) {
         return 'My name is ' + this.firstName + " " + this.lastName;
      }
  };
  document.getElementById("main").innerHTML = person.fullName ();
  </script>

</body>

No comments:

Post a Comment