Take the 2-minute tour ×

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?

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

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:

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

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.

share|improve this answer
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 Oct 1 '09 at 15:57
In case of 5 elements it doesn't matter. In general, since getElementById is used very often, browsers optimize it the most. –  Nickolay Oct 12 '09 at 6:44
add comment

Your Answer


