Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda