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

Revision 32 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="el">
  Some HTML element
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var el = document.getElementById('el'),
      did = 'el',
      jid = '#el';

  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
</script>

Setup

el.id = did = S4();
    jid = '#' + did;

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery('#id')
jQuery(jid).length;
ready
jQuery(document.getElementById('id'))
jQuery(document.getElementById(did)).length;
ready
$(document.getElementById('id')).length
$(document.getElementById(did)).length;
ready
document.getElementById('id')
document.getElementById(did);
ready

Revisions

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