Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  131] [ 6]  / answers: 1 / hits: 23249  / 10 Years ago, fri, december 19, 2014, 12:00:00

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.


More From » javascript

 Answers
15

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>

[#68439] Tuesday, December 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aricl

Total Points: 215
Total Questions: 91
Total Answers: 94

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;