JQuery $('#id') selector vs $(document.getElementById('id')
JavaScript performance comparison
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="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>
<script>
Benchmark.prototype.setup = function() {
el.id = did = S4();
jid = '#' + did;
};
</script>
Preparation code output
Some HTML element
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
jQuery('#id') |
|
pending… |
document.getElementById('id') |
|
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:
- Revision 1: published by streetpc
- Revision 2: published by Hadrien.eu
- Revision 3: published
- Revision 4: published by Hadrien.eu
- Revision 5: published
- Revision 6: published
- Revision 7: published by Devin Rhode
- Revision 8: published
- Revision 9: published
- Revision 10: published
- Revision 11: published
- Revision 12: published
- Revision 13: published
- Revision 14: published
- Revision 15: published
- Revision 16: published
- Revision 17: published by Rajesh Taneja
- Revision 18: published by Abdullah
- Revision 19: published
- Revision 20: published
- Revision 22: published
- Revision 23: published
- Revision 24: published
- Revision 25: published by David S
- Revision 26: published
- Revision 27: published
- Revision 28: published
- Revision 29: published
- Revision 30: published by NJH
0 comments