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 Answers
Know the answer? Post it. Somebody with the same question will find it here.

Midhun TpRank #388 · 6.5K reputationPosted Oct 16, 2016, 5:32 PM EDT
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.
ali tuncerRank #1,498 · 1.1K reputationPosted Oct 16, 2016, 5:35 PM EDT
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;
}