Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript :TypeError: document.getElementById(...) is null [duplicate]

Tags:

javascript

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.

like image 510
Saurabh Shrikhande Avatar asked Dec 04 '25 10:12

Saurabh Shrikhande


1 Answers

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>
like image 130
Denys Séguret Avatar answered Dec 06 '25 23:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!