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

140
Visualizações
Is there a performance benefit to narrowing the scope of a `querySelector()` search first?

(If it makes any difference, I'm working on a web component.)

If I have the following:

<!-- Assume a decently-sized web page with lots of elements before and after all this -->
<form>
   <input type="hidden" id="foo" name="foo" value="bar" />
</form>
<script>
let myForm = document.querySelector('form');
</script>

…and I want to select the hidden field, which is faster/better?

A)

let field = document.querySelector('#foo');

B)

let field = myForm.querySelector('#foo');
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the case of an ID selector, I think A is likely to be faster.

IDs are supposed to be unique, so the browser almost certainly has an index of all the IDs. Looking up an ID in document will use this index to find the element as quickly as possible.

But if you query for the ID nested in another element, it will assume that you're violating this expectation, and it will have to do an actual search within that element. This is difficult to optimize, and there's little incentive to do so since it's not a valid DOM.

It's possible that the browser will keep track of which IDs have been duplicated. If foo is not duplicated, B could be optimized to be equivalent to A.

So B is at best equivalent to A, but it could be worse.

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