Javascript efficiency issue: multiple getElementById () versus getElementsByTagName () and looping result

I was wondering if it would be more efficient to use document.getElementById () n the number of times, or to use document.getElementsByTagName () and see the search result for Element IDs?

+2


source to share


1 answer


It all depends. How many elements with the specified IDs do you have? How many elements have the same name?

For example, if you want elements with IDs 1 and 3, and you have:

<ul>
  <li id="1">1</li>
  <li id="2">2</li>
  <li id="3">3</li>
  <!-- Followed by 10,000 more li tags -->
</ul>

      



you better not call getElementById()

twice. But if you want everything but ID 15, you are probably better off listing and checking for IDs.

Another alternative is to add a class to specific elements that you want to select. Then you can select by class (possibly with a JQuery class selector ) which will give you good performance throughout the round.

Be aware that Javascript performance is very different between browsers and even between browser versions . It is best to test against target browsers.

+5


source







All Articles