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

Revision 30 of this benchmark created by NJH 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

<section>
        <hgroup>
                <h1>title</h1>
                <h2>subtitle</h2>
        </hgroup>
        <p>some text
        </p>
        <nav>
                <ul>
                        <li><a href="">links</a></li>
                        <li><a href="">links</a></li>
                        <li><a href="">links</a></li>
                </ul>
        </nav>
        <img src="" alt="" />
</section>
<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 = S4();
    jid = '#' + did;
    djid = 'div#' + did;

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery('#id')
jQuery(jid);
ready
document.getElementById('id')
document.getElementById(did);
ready
jQuery('div#id')
jQuery(djid);
ready
jquery prototype
jQuery($(did));
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.