getElementById vs. querySelector vs getElement(s)ByClassName vs scoping

JavaScript performance comparison

Revision 163 of this test case created by Nk_bet

Preparation code

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

Preparation code output

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

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
getElementById
var bar = document.getElementById("bar");
pending…
getElementsByClassName (first element)
var bar = document.getElementsByClassName("bar")[0];
pending…
querySelector
var bar = document.querySelector("#bar");
pending…
getElementsByClassName (last element)
var bar = document.getElementsByClassName("bar")[2];
pending…
getElementById.querySelector
var bar = document.getElementById("main").querySelector("#bar");
pending…
getElementById.getElementsByClassName (first element)
var bar = document.getElementById("main").getElementsByClassName("bar")[0];
pending…
getElementById.getElementsByClassName (last element)
var bar = document.getElementById("main").getElementsByClassName("bar")[2];
pending…

Compare results of other browsers

Revisions

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

0 Comments

Foo

Bar

Baz

window._gaq=[['_setAccount','UA-6065217-40'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='https://ssl.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'))