frenchie
frenchie

Reputation: 51997

is jquery .find always useful?

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();

Upvotes: 5

Views: 88

Answers (4)

Code Maverick
Code Maverick

Reputation: 20415

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');

Upvotes: 3

Kh&#244;i
Kh&#244;i

Reputation: 2153

Essentially there is no difference. But find() is useful if you use it with scoped variables and this.

For example:

$(document).ready( function() {
    $('.action').click( function() {
        $(this).find('p').text("hello world");
    });
});

Which sets all p within anything which has a class named action to "hello world".

Upvotes: 2

Jakub Konecki
Jakub Konecki

Reputation: 46008

They are both equivalent. The first one will be slightly slower, since you're doing two queries. The difference in speed is probably not noticable.

You can use find in cases when you're creating a plugin / component that gets it's container in the constructor and than you use it as the root of your searches with find to make sure that you don't get any elements outside your container.

Upvotes: 2

oezi
oezi

Reputation: 51817

in you case, using find() is pretty senseless (except for readability - but anyone will have another opinion on that). i only use find() in cases where it's really needed, like:

$('#MyDiv').show().find('.SClass1').css(...);

where something has to be done with the parent-element first and something else with one or more of its children.

Upvotes: 2

Related Questions