-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> 

2
  • 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. Commented Aug 15, 2018 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. Commented Aug 15, 2018 at 15:14

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.