getElementById vs. querySelector

JavaScript performance comparison

Test case created by Ara Pehlivanian

Preparation code

<p id="foo">Foo</p>
<p id="bar">Bar</p>
<p id="baz">Baz</p>

Preparation code output

<p id="foo">Foo</p> <p id="bar">Bar</p> <p id="baz">Baz</p>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
var bar = document.getElementById("bar");
var bar = document.querySelector("#bar");

Compare results of other browsers


You can edit these tests or add even more tests to this page by appending /edit to the URL.


Spamme commented :

Interesting, I was actually looking for something else, a benchmark between the document methods querySelector and evaluate. It would be interesting if you add to your test also the xpath search technique, not every browser is implementing it but if I'm not wrong firefox, opera, safari and chrome have implemented it, as usual ie doesn't follow the standards but who care?

Xpath to get an element by id: //*[@id='bar'] JavaScript code: document.evaluate("//*[@id='bar']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

Krishnan commented :

You saved me from using querySelctor. I am new to web development. How do you arrive at the speed calculation? I could understood one thing that querySelector is way behind getElementById. But how do you arrive at this conclusion. Just typically running a timer to test that?

wes commented :

Interesting, I was under the impression IE9 does not support querySelector(), which is the search that led me to this page. Do you have some other Javascript library installed for this support in IE9???

Eric commented :

What I wonder is what is faster in this situation:

var id3 = document.getElementById( "id3" );
var id4 = document.getElementById( "id3" );
var id5 = document.getElementById( "id3" );


var id2 = document.getElementById( "id2" );
var id3 = id2.querySelector( "#id3" );
var id4 = id2.querySelector( "#id4" );
var id5 = id2.querySelector( "#id5" );