I have some HTML like this:
<div id="MyDiv">
<div class="Class1">
<div class="SClass1"></div>
</div>
<div class="Class2"></div>
</div>
Is there any difference between
$('#MyDiv').find('.SClass1').show();
and
$('#MyDiv .SClass1').show();
The find() is an inbuilt method in jQuery which is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree. Here selector is the selected elements of which all the descendant elements are going to be found.
The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.
ID and Element selector are the fastest selectors in jQuery.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
http://api.jquery.com/jquery/#selector-context states that:
Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').
Which means
$('#MyDiv .SClass1').show();
Is only one step away from jQuery internally making it
$('#MyDiv').find('.SClass1').show();
View this jsPerf test case to see the differences in speed
As @Dominic mentioned in the comments, in his jQuery Anti-Patterns for Performance & Compression presentation, Paul Irish states:
Selector Optimization
Of course, descending from an #id is best
// #id-based selector
var arms = $('#container div.robotarm');
// hyper-optimized #id case first, then find:
var arms = $('#container').find('div.robotarm');
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