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

136
Views
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 answers
Answer question

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 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!