Search code examples
javascriptjqueryhtmlcssappendchild

Cannot set property innerHTML of null on appended child (div)


Before I learn some Unity I wanted to be able to create a simple Javascript game out of my own knowledge. So, I started experimenting with a timer and it worked. Then I wanted to add a div element to my HTML document and have its text change in response to the timer. So I wrote this code:

var counter = 0;
var seconds = 0;

$(document).ready(function(e) {
  var element = document.createElement("div");
  element.id = "text2";
  document.getElementById("canvas").appendChild(element);

  function gameActions() {
    document.getElementById("canvas").innerHTML = seconds;
    if (seconds == 1) document.getElementById("text2").innerHTML = "second";
    else document.getElementById("text2").innerHTML = "seconds";

    counter++;

    if (counter % 50 == 0) {
      seconds++;
    }

  }

  setInterval(gameActions, 20);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="canvas" class="imgcenter" style="width: 500px; height: 400px; background-color: #eeffee;">

</div>

Basically I'm intending to change the text of the "parent" div which displays the number of seconds passed after the html page is fully loaded. But before that, I'm trying to create a div with id text2 to add it inside the div parent.This div should display the word "seconds" depending on the time (basically display "second" when the seconds variable is 1, and "seconds" when not)

Where "imgcenter" is only CSS to specify auto margin. The error is that, whenever I run this on Chrome, I get:

Uncaught TypeError: Cannot set property 'innerHTML' of null

Am I correct to assume the div is not being added? Am I missing a step in the addition? Please let me know what you think the error is, thank you


Solution

  • This code:

    var element = document.createElement("div");
    element.id = "text2";
    document.getElementById("canvas").appendChild(element);
    

    … puts the element you are trying to target inside the canvas div.

    This code:

        document.getElementById("canvas").innerHTML = seconds;
    

    destroys everything in that element and replaces it with the HTML in the seconds variable.

    Am I correct to assume the div is not being added?

    No. The div is added, but then you destroy it before trying to do anything with it.