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

Revision 28 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 src="//ajax.googleapis.com/ajax/libs/prototype/1/prototype.js"></script>

<script>
jQuery.noConflict();

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 = "i" + S4();
    jid = '#' + did;

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery('#id')
jQuery(jid);
ready
document.getElementById('id')
document.getElementById(did);
ready
querySelector
document.querySelector(jid);
ready
doc jquery
jQuery(document.getElementById(did));
ready

Revisions

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