0

Lets say I had a group of buttons in this structure, that I wanted to access through JavaScript

<div id="container">
  <button id="one">One</button>
  <button id="two">Two</button>
  <button id="three">Three</button>
  <button id="four">Four</button>
  <button id="five">Five</button>
  <button id="six">Six</button>
  <button id="seven">Seve</button>
  <button id="eight">Eight</button>
  <button id="nine">Nine</button>
  <button id="ten">Ten</button>
</div>

Efficiency-wise, would it be better to:

A) Use document.getElementById for it to scan the DOM each time, and get the buttons

B) Use document.getElementById to get a reference to container, then use querySelector on container to get each button, which saves having to search the DOM continuously?

Or is it indifferent?

Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
  • 2
    https://stackify.com/premature-optimization-evil/ – Quentin Apr 17 '23 at 09:51
  • 1
    Fun fact (?) For this exact case it either doesn't matter at all because the engine has a shortcut `querySelector(`#`)` -> `getElementById` (e.g in Chromium based browsers), or `getElementById` will win because it's a simple key access (the document has to keep all named elements in a map), but the cases where this would matter are if you're on a page as huge as the full monopage Ecma Standards, on a slow device. But you'll certainly face other problems before having time to handle that one. Don't bother with that. – Kaiido Apr 17 '23 at 10:11

0 Answers0