Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is jquery .find always useful?

Tags:

jquery

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();
like image 573
frenchie Avatar asked Apr 04 '12 13:04

frenchie


People also ask

Why we use find in jQuery?

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.

Does jQuery always return an array?

The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector.

Which jQuery selector is fastest?

ID and Element selector are the fastest selectors in jQuery.

What is $() 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.


1 Answers

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');
like image 163
Code Maverick Avatar answered Oct 21 '22 04:10

Code Maverick