querySelectorAll vs getElementsByTagName

JavaScript performance comparison

Revision 43 of this test case created

Info

Checking how querySelectorAll('parent child') or '.parent .child' selection performs against combinations of getElementsByTagName, getElementsByClassName and jQuery

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<ul class="root-ul"><li><a class="link word" href="#word">word</a>
</li><li><a class="link glass" href="#glass">glass</a>
</li><li><a class="link lorum" href="#lorum">lorum</a>
</li><li><a class="link ipsum" href="#ipsum">ipsum</a>
</li><li><a class="link dolor" href="#dolor">dolor</a>
</li><li><a class="link sit-amet" href="#sit-amet">sit-amet</a>
</li></ul>
<script>
Benchmark.prototype.teardown = function() {
    window.console && console.log && console.log('nodes:',nodes.length, nodes);
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
querySelectorAll
var root = document.querySelectorAll('ul .link'),
    nodes = [], l, i, push = Array.prototype.push;
for (i = 0, l = root.length; i < l; i++) {
  push.apply(nodes, root[i]);
}
pending…
getElementsByTagName + getElementsByTagName
var root = document.getElementsByTagName('ul'),
    nodes = [], l, i, push = Array.prototype.push;
for (i = 0, l = root.length; i < l; i++) {
  push.apply(nodes, root[i].getElementsByTagName('a'));
}
pending…
getElementsByTagName + getElementsByClassName
var root = document.getElementsByTagName('ul'),
    nodes = [], l, i, push = Array.prototype.push;
for (i = 0, l = root.length; i < l; i++) {
  push.apply(nodes, root[i].getElementsByClassName('link'));
}
pending…
getElementsByClassName + getElementsByClassName
var root = document.getElementsByClassName('root-ul'),
    nodes = [], l, i, push = Array.prototype.push;
for (i = 0, l = root.length; i < l; i++) {
  push.apply(nodes, root[i].getElementsByClassName('link'));
}
pending…
getElementsByClassName + getElementsByTagName
var root = document.getElementsByClassName('root-ul'),
    nodes = [], l, i, push = Array.prototype.push;
for (i = 0, l = root.length; i < l; i++) {
  push.apply(nodes, root[i].getElementsByTagName('a'));
}
pending…
jQuery by CSS class
var nodes = jQuery('.root-ul .link');
pending…
jQuery by Tag + class
var nodes = jQuery('ul .link');
pending…
jQuery by class + Tag
var nodes = jQuery('.root-ul a');
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. Here’s a list of current revisions for this page:

0 comments

Add a comment