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

Revision 12 of this benchmark created on


Description

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 HTML

<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>

Test runner

Ready to run.

Testing in
TestOps/sec
$('#el4').length;
$('#el4').length;
ready
$('.el5').length;
$('.el5').length;
ready
$('#el1 #el3 #el4').length;
$('#el1 #el3 #el4').length;
ready
$('#el1 #el3 .el5').length;
$('#el1 #el3 .el5').length;
ready
$('#el3 .el5').length;
$('#el3 .el5').length;
ready
$('#el3 #el4').length;
$('#el3 #el4').length;
ready
$('.el8 .el7 .el6 .el5').length;
$('.el8 .el7 .el6 .el5').length;
ready
$(document.getElementById('el4')).length;
$(document.getElementById('el4')).length;
ready
$('.el6 .el5').length;
$('.el6 .el5').length;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.