Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

308
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda