getElementById vs. querySelector (v101)

Revision 101 of this benchmark created on


Description

Compare the speed of getElementById to querySelector

Preparation HTML

<p id="foo">Foo <span class="secondary">Bar</span></p>
<p id="bar">Bar <span class="secondary">Baz</span></p>
<p id="baz">Baz <span class="secondary">Qaz</span></p>

Setup

document.body.id = "body";

Teardown


    document.body.id = "";
  

Test runner

Ready to run.

Testing in
TestOps/sec
Id("bar").ClassName("secondary")[0]
var el = document.getElementById("bar").getElementsByClassName("secondary")[0];
if (!el) throw new Error("NO ELEMENT");
 
ready
Selector("#bar .secondary")
var el = document.querySelector("#bar .secondary");
if (!el) throw new Error("NO ELEMENT");
 
ready
body.Selector("#bar .secondary")
var el = document.body.querySelector("#bar .secondary");
if (!el) throw new Error("NO ELEMENT");
 
ready
Selector("#bar > .secondary")
var el = document.querySelector("#bar > .secondary");
if (!el) throw new Error("NO ELEMENT");
 
ready
body.Selector("#bar > .secondary")
var el = document.body.querySelector("#bar > .secondary");
if (!el) throw new Error("NO ELEMENT");
 
ready

Revisions

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