getElementById vs. getElementsByClassName vs. querySelector vs. jQuery

JavaScript performance comparison

Revision 306 of this test case created by Ryan Badour

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<p id="foo" class="my-foo">
  Foo
</p>
<p id="bar" class="my-bar">
  Bar
</p>
<div id="poo" class="my-poo">
  <div id="par" class="my-bar">
    <div id="paz" class="my-bar">
      <span id="baz" class="my-baz">
        Baz
      </span>
    </div>
  </div>
</div>
    

Preparation code output

<p id="foo" class="my-foo"> Foo </p> <p id="bar" class="my-bar"> Bar </p> <div id="poo" class="my-poo"> <div id="par" class="my-bar"> <div id="paz" class="my-bar"> <span id="baz" class="my-baz"> Baz </span> </div> </div> </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
querySelector (just class)
var poo = document.querySelector(".my-baz");
pending…
getElementsByClassName
var bar = document.getElementsByClassName("my-baz");
pending…
querySelector (id + class)
var poo = document.getElementById("poo").querySelector(".my-baz");
pending…
jQuery Class Selector
var bar = $("#poo .my-baz");
pending…
Child finder
function findChild(ele, predicate, deep = false) {
    for (var i = 0; i < ele.children.length; ++i) {
        if (predicate(ele.children[i], i)) {
            return ele.children[i];
        }

        if (deep) {
            const result = findChild(ele.children[i], predicate, true);
            if (result !== null) {
                return result;
            }
        }
    }

    return null;
}

var baz = findChild(document.body, function (c) {
   return c.classList.contains("my-baz");
}, true);
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