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.
var c=2;d=3,e=c+d;
document.getElementById('p1').innerHTML=e;
2 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
ali tuncerPosted Oct 16, 2016, 9:35 PM
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;
}
Midhun TpPosted Oct 16, 2016, 9:32 PM
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.