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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With