Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery element+class selector performance

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?

Performance analysis for class selectors

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') 
like image 207
Lanka Avatar asked Jul 28 '12 06:07

Lanka


People also ask

Which jQuery selector is fastest?

ID and Element selector are the fastest selectors in jQuery.

Is jQuery slower than JavaScript?

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.

Does jQuery cache selector?

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.


1 Answers

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.

like image 70
Frédéric Hamidi Avatar answered Sep 29 '22 20:09

Frédéric Hamidi