Which is better to use as a performance perspective:
$(".div1 h2, .div1 h3")
or
$(".div1").find("h2, h3")
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.
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.
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)
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();
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