1

I don't understand why this simple script works only when I place it in the body?

when i place the script within the head or in external JS file it doesn't work.

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
tomer
  • 129
  • 1
  • 2
  • 9

1 Answers1

0

Because the element you reference is defined only later (at the time the <head> is processed the browser hasn't processed the markup underneath it yet).

obe
  • 7,378
  • 5
  • 31
  • 40