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="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>
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 | |
|---|---|---|
$('#el4').length; |
|
pending… |
$('.el5').length; |
|
pending… |
$('#el1 #el3 #el4').length; |
|
pending… |
$('#el1 #el3 .el5').length; |
|
pending… |
$('#el3 .el5').length; |
|
pending… |
$('#el3 #el4').length; |
|
pending… |
$('.el8 .el7 .el6 .el5').length; |
|
pending… |
$(document.getElementById('el4')).length; |
|
pending… |
$('.el6 .el5').length; |
|
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
- Revision 31: published
- Revision 32: published
0 comments