Q:

JavaScript :TypeError: document.getElementById(...) is null

Following is my code.
<html>

<head>
<script>
    var x = 5;
    var y = 6;
    var z = x + y;
    document.getElementById("add").innerHTML = z;
</script>
</head>

<body>
    <h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>

</body>

</html>

And when I am trying to display the value of z in (span add) I am getting following error.
 TypeError: document.getElementById(...) is null

Please help me.

A:

Change the order : put the script after the element so that it's defined when getElementById is called.
<body>
    <h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>
<script>
    var x = 5;
    var y = 6;
    var z = x + y;
    document.getElementById("add").innerHTML = z;
</script>
</body>

Another solution would be to use jQuery's ready function :
<script>
    $(function(){
        var x = 5;
        var y = 6;
        var z = x + y;
        $('#add').html(z); // if you use jQuery, you may as well do that
    });
</script>
</head>
<body>
    <h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>

</body>

A:

Add your code to onload event like this 
window.onload = function () {
    var x = 5;
    var y = 6;
    var z = x + y;
    document.getElementById("add").innerHTML = z;
}

Demo: http://jsbin.com/luqeyo/1/edit?html,output
Because you try call document before it ready to use. 
Update: if you don't want wait, while will load all resources (images etc.) you can use this approach
  document.onreadystatechange = function () {
    if (document.readyState === "complete") {
      ready();
    }
  }

  function ready() {
      var x = 5;
      var y = 6;
      var z = x + y;
      document.getElementById("add").innerHTML = z;
  }

Demo: http://jsbin.com/luqeyo/2/edit?html,output

