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

JavaScript performance comparison

Revision 12 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="el1" class="el8">
  <div id="el2" class="el7">
  </div>
  <div id="el3" class="el6">
    <div id="el4" class="el5">
      Some HTML element
    </div>
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Preparation code output

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
$('#el4').length;
$('#el4').length;
pending…
$('.el5').length;
$('.el5').length;
pending…
$('#el1 #el3 #el4').length;
$('#el1 #el3 #el4').length;
pending…
$('#el1 #el3 .el5').length;
$('#el1 #el3 .el5').length;
pending…
$('#el3 .el5').length;
$('#el3 .el5').length;
pending…
$('#el3 #el4').length;
$('#el3 #el4').length;
pending…
$('.el8 .el7 .el6 .el5').length;
$('.el8 .el7 .el6 .el5').length;
pending…
$(document.getElementById('el4')).length;
$(document.getElementById('el4')).length;
pending…
$('.el6 .el5').length;
$('.el6 .el5').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