Take the 2-minute tour ×

I often use the method getElementById("id1"); in my methods. I use it to find certain elements in my HTML. I wonder if I need to be concerned about how much I use it if it has to search the entire DOM every time.

How does this method work? Does it parse the DOM and return the element when it is found, or does it have all those values indexed somehow and so is able to return more quickly?

P.S. I am curious about the method in general, but I am using an Android WebView if that makes any difference.

share|improve this question
So you don't want to use jQuery? They did it for you. getElementById("id1"); == $('#id1') –  Bondye Sep 20 '12 at 14:38
I am unable to use jQuery or other imported Libraries. It has to be bland JavaScript. Sad, huh? –  Jon Sep 20 '12 at 14:40
WHAT?!?! You can use javascript but you can't use javascript? –  Bondye Sep 20 '12 at 14:41
@Bondye: What do you mean? jQuery doesn't make it faster. It's basically boils down to getElementById plus constructing a set etc. –  pimvdb Sep 20 '12 at 14:42
add comment

3 Answers

up vote 4 down vote accepted

getElementById is very fast and you shouldn't have to worry about performance.

If you are using the same ID over and over (and over and over) again, you might want to cache it. The performance gain is neglectable:

var myId = getElementById("myId");

Check this SO answer for some benchmarks. The results Mike posted were:

IE8 getElementById: 0.4844 ms
IE8 id array lookup: 0.0062 ms

Chrome getElementById: 0.0039 ms
Chrome id array lookup: 0.0006 ms

Firefox 3.5 was comparable to chrome.

share|improve this answer
neglectable (something you can neglect) != negligable (something so small as to be unmesurable) –  Jamiec Sep 20 '12 at 14:46
add comment

In fact getElementById is the fastest way to access an element in the DOM. Indexing depends on the specific browser, but here is a benchmark for it:


share|improve this answer
add comment

Elements with IDs are indeed indexed, selecting an element by its ID through the DOM function is the most efficient way of selection.

share|improve this answer
add comment

Your Answer


