I was hoping $('#childDiv2 .txtClass')
or $('#childDiv2 input.txtClass')
perform better when selecting <input type="text" id="txtID" class="txtClass"/>
element. But according to this performance analysis $('.txtClass');
is the best selector among this. I'm using JQuery 1.7.2 Does anybody have explanation for this?
HTML
<div class="childDiv2"> <input type="text" id="txtID" class="txtClass"/> <p class="child">Blah Blah Blah</p> </div>
JS
$('.txtClass'); $('#childDiv2 .txtClass') $('#childDiv2 > .txtClass') $('input.txtClass') $('#childDiv2 input.txtClass')
ID and Element selector are the fastest selectors in jQuery.
A. When it comes to speed, jQuery is quite fast for modern browsers on modern computers. So is pure JavaScript but both run very slow on older browsers and machines. Pure Javascript functions will be faster than jQuery operations.
Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.
Modern browsers expose a very efficient getElementsByClassName() method that returns the elements having a given class. That's why a single class selector is faster in your case.
To elaborate on your examples:
$(".txtClass") => getElementsByClassName() $("#childDiv2 .txtClass") => getElementById(), then getElementsByClassName() $("#childDiv2 > .txtClass") => getElementById(), then iterate over children and check class $("input.txtClass") => getElementsByTagName(), then iterate over results and check class $("#childDiv2 input.txtClass") => getElementById(), then getElementsByTagName(), then iterate over results and check class
As you can see, it's quite logical for the first form to be the fastest on modern browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With