'Are DOM elements preceding a <script> tag guaranteed to exist before the script runs?

Does the HTML spec guarantee that DOM elements appearing before a <script> tag are present before the content of that script is executed (and can be manipulated by that script)?

This works in all browsers I've tested, but I'm not sure whether it's legal:

<main hidden>Hello, world</main>
<script type="text/javascript">
  document.querySelector('main').hidden = false;  // no error thrown
</script>

I know that the script will execute immediately, blocking parsing, unless it has the async or defer attributes.

But does the parsing up until this point guarantee that the prior elements are in the DOM and ready to be manipulated, or is it safest to wait for DOMContentLoaded?



Solution 1:[1]

As far as I know, it will run just after parsing the previous node. You can use even document.write function to feed the parser with code.

As you can try below, it can even close tags. It directly feeds the output from document.write() to the parser.

Foo
<script>
  document.write("<strong>bar</strong>")
</script>

<em>something
<script>
  document.write("weird</em>")
</script>
here.

You can access the DOM in scripts even when the loading is in progress, but I would personally avoid it. As you can see below, element that was not yet closed can be accessed.

This works:

<em id="foo">foo</em>
<script>
  document.write(document.getElementById("foo"))
</script>

<hr />

<em id="unclosed">unclosed element
<script>
  document.write(document.getElementById("unclosed"))
</script>
</em>

But avoid long-running scripts, because the parser (and therefore rendering) will stop and it can be unpleasant if the scripts does its work for few seconds.

In this example, you can see that you can hide, and even remove, the element even just after the opening tag:

<p id="toHide">
  <script>
    document.getElementById("toHide").remove()
  </script>
  
  This is hidden.
</p>

This is not hidden.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1