JQuery $('#id') selector vs $(document.getElementById('id')

JavaScript performance comparison

Revision 22 of this test case created

Info

Fastest way get a jQuery object of a DOM element of which I have the ID. document.getElementById has the advantage of not requiring escaping for special characters.

Preparation code

<div id="el">Some HTML element<div id="el2">Some HTML element</div></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var d = {};
    d.id = function (el) {
      return document.getElementById(el);
    }
};
</script>

Preparation code output

Some HTML element
Some HTML element

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery('#id')
jQuery('#el').length;
pending…
jQuery(document.getElementById('id'))
jQuery(document.getElementById('el')).length;
pending…
No jQuery
document.getElementById('el').length;
pending…
wrapped getElementById
d.id('el').length
pending…
document.querySelector()
document.querySelector('#el').length
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