Selector Specificity Comparison

JavaScript performance comparison

Test case created by Tyler Wood

Info

Comparison between several different methods of querying the DOM.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="idDiv">
 <ul>
  <li></li>
  <li class="selected"></li>
  <li></li>
 </ul>
</div>
<div class="classDiv">
 <ul>
  <li></li>
  <li class="selected"></li>
  <li></li>
 </ul>
</div>
<script>
Benchmark.prototype.setup = function() {
    var idDiv = $('div#idDiv');
};
</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
getElementById
var elem = document.getElementById('idDiv');
pending…
jQuery ID Selector
var elem = $('#idDiv');
pending…
jQuery Specific ID Selector
var elem = $('div#idDiv');
pending…
jQuery Class Selector
var elem = $('.classDiv');
pending…
jQuery Specific Class Selector
var elem = $('div.classDiv');
pending…
getElementsByClassName
var elem = document.getElementsByClassName('classDiv');
pending…
Nested jQuery Strong Left
var elem = $('div.classDiv .selected');
pending…
Nested jQuery Strong Right
var elem = $('.classDiv li.selected');
pending…
Nested jQuery Strong Both
var elem = $('div.classDiv li.selected');
pending…
Nested jQuery Non-Cache Context
var elem = $('.selected', '#idDiv');
pending…
Nested jQuery Cached Context
var elem = $('.selected', idDiv);
pending…
querySelector ID
var elem = document.querySelector('#idDiv');
pending…
querySelector Specific ID
var elem = document.querySelector('div#idDiv');
pending…
querySelector Class
var elem = document.querySelector('.classDiv');
pending…
querySelector Specific Class
var elem = document.querySelector('div.classDiv');
pending…
querySelectorAll > li
var elem = document.querySelectorAll('li');
pending…
jQuery > li
var elem = $('li');
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