Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery single selector vs .find()

Which is better to use as a performance perspective:

$(".div1 h2, .div1 h3") 

or

$(".div1").find("h2, h3") 
like image 301
Dan Avatar asked Jun 03 '11 17:06

Dan


People also ask

Which is the fastest selector in jQuery?

ID Selector: The jQuery #id selector selects the element on the basis of the ID attribute of the HTML tag. This selector is basically used when we have to work on a single element because an ID should be unique within a web page.

Why we use find in jQuery?

find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The . find() and . children() methods are similar, except that the latter only travels a single level down the DOM tree.


2 Answers

http://jsperf.com/selector-vs-find-again

selector is faster

(NOTE: made up random html just so it wasn't just those elements on the page)

like image 98
James Montagne Avatar answered Sep 18 '22 18:09

James Montagne


The answer to your question is: yes.

Don't worry about the performance difference, unless your code is slow. If it is, use a profiler to determine bottlenecks.

From an analysis standpoint:

$(".div1 h2, div1 h3") 

should be faster as jQuery will pipe it through querySelectorAll (if it exists) and native code will run faster than non-native code. It will also save on an additional function call.

$(".div1").find("h2, h3") 

is better if you plan on chaining some other functions on .div1:

$(".div1").find("h2, h3").addClass('foo').end().show(); 
like image 43
zzzzBov Avatar answered Sep 16 '22 18:09

zzzzBov