views:

589

answers:

1

I was wondering if it would be more efficient to use document.getElementById() n number of times or to use document.getElementsByTagName() and loop through the result looking for the specific Element ids?

+3  A: 

It all depends. How many elements with given IDs do you have? How many elements with the same tag 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 would be better off calling getElementById() twice. But if you want everything except ID 15, you would probably be better off doing the list and checking IDs.

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

Keep in mind that Javascript performance vary wildly between browsers and even between versions of browsers. Best to do some testing against your target browsers.

leonm
Thanks For the reply Leonm. There are 5 specific id's, but no way to tell how many elements could be on the page. I'm going to test this out, thanks again.
Likescheese
In case of 5 elements it doesn't matter. In general, since getElementById is used very often, browsers optimize it the most.
Nickolay