2
Answers

javascript question

umair mohsin

umair mohsin

8y
256
1
i wonna know what is the problem with this javascript code its not working until i wrote a script in a body tag. the script should run whether i wrote script in head or a body section.i don't know what is the issue.here is my code.
 
 
<html>
<head>
<title>Statements in javascript</title>
<style type="text/css"></style>
<script type="text/javascript">
var c=2;d=3,e=c+d;
document.getElementById('p1').innerHTML=e;
</script>
</head>
<body>
<p id="p1"></p>
</body>
</html>
Answers (2)
0
ali tuncer
NA 2.9k 108 8y

you need to wait for page to load first,try this way :

window.onload = function () {
var c = 2; d = 3, e = c + d;
document.getElementById('p1').innerHTML = e;
}

if you are using jquery, you can use
(document).ready(function() {
//your code here
});
0
Midhun T P
NA 19.7k 281.2k 8y
Hi,<br><br> Script will work if it is written on body or head tag. But the problem is that, you are trying to assign innerhtml of p tag from head. That wont work, as while running your script in head tag that p element is not loaded in the body. Hence script can't find any p element with that id.