-1

If I'm trying to affect an HTML element with a script (getElementById) it only works if the script comes after the element. Isn't javascript code usually all at the top of the HTML doc? For example:

Why does this work:

<!DOCTYPE html>
<html>
<body>
<p id="helloMessage"> </p>
<script>
document.getElementById("helloMessage").innerHTML = "Hello, World!";
</script>
</body>
</html>

but this does not

<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("helloMessage").innerHTML = "Hello, World!";
</script>
<p id="helloMessage"> </p>
</body>
</html> 
Zaren Wienclaw
  • 181
  • 4
  • 15
AndoKay
  • 57
  • 2
  • 9
  • 3
    That's because, in the second snippet, when JavaScript starts executing, the element is not present in the document (DOM). That's why your JS code cannot modify it. You cannot eat a pizza until you have it. – 31piy Aug 15 '18 at 15:12
  • HTML is parsed line by line by the browser. If the script is before, the HTML element does not exist yet when the script is executed. – Jeremy Thille Aug 15 '18 at 15:14

1 Answers1

0

If the snippet is very specific snippet is placed before the element , then this line document.getElementById("helloMessage") will try to find an element from DOM whose id is helloMessage , since the element is not there it will not work

You can still put it before the html by putting this code inside window.onload

<html>

<body>
  <script>
    window.onload = function() {
      document.getElementById("helloMessage").innerHTML = "Hello, World!";
    }
  </script>
  <p id="helloMessage"> </p>
</body>

</html>
brk
  • 48,835
  • 10
  • 56
  • 78