Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!