Jeff
Jeff

Reputation: 12183

Difference between $('div div') and $('div').find('div')?

I was just poking around with jQuery, and I stumbled upon the Find function.

I tested like this:

$(document).ready(function(){

    $('button').click(function(){

        $('div').find('div').fadeOut(2000);

    });
});

And this

$(document).ready(function(){

    $('button').click(function(){

        $('div div').fadeOut(2000);

    });
});

And both produce the exact same result.

Whats the difference? :)

Upvotes: 2

Views: 239

Answers (4)

Jack Franklin
Jack Franklin

Reputation: 3765

They both do exactly the same thing, but in older browsers where document.querySelectorAll() is not available (Old IEs) $("div").find("div"); is quicker, as Paul Irish confirms in this comment here.

Another thing to note is that in jQuery you can also do this:

$("div", "#some-element")

Which would search for div inside of #some-element. jQuery actually converts this into:

$("#some-element").find("div")

So it's always suggested to use .find() rather than pass in a context.

Upvotes: 1

Christopher Armstrong
Christopher Armstrong

Reputation: 7953

In this specific case, they do the same thing. Note that find() will traverse all the descendants of the matched elements.

Upvotes: 0

SLaks
SLaks

Reputation: 887767

There is no difference.

If you already have a jQuery object, the find method is useful.
Otherwise, a single selector is simpler.

Most selectors have method equivalents (.children(), .first(), .not()) for this reason.

The method versions also allow you to call .end() to go back to the previous object.

Upvotes: 2

Mo Valipour
Mo Valipour

Reputation: 13496

In your example there is no difference but there are cases that you can not use the first one, for example let't say you have an element as the parameter of a function and you want to find divs inside it, then you have to use the "Find" method.

function foo(index, el)
{
    $(el).find("div")...
}

But when you know the exact path, obviously the second approach is more robus.

Upvotes: 3

Related Questions