joshb
joshb

Reputation: 5220

jQuery filter method confusion

I'm trying to filter a jQuery object using the filter method but am not getting the results I expect. Here's my code:

var $contents = $(".container");
var $spans = $contents.filter("span");

Based on my understanding of the jQuery filter method this should be equivalent to the following:

var $spans = $(".container span");

However, the first example returns no results into the $spans variable while the second does what I would expect.

Can anyone explain why the first example doesn't return a collection of all the span elements in the container?

Here's a jsfidle illustrating the problem: http://jsfiddle.net/w8Sf7/

Upvotes: 0

Views: 123

Answers (4)

JoeFletch
JoeFletch

Reputation: 3960

.filter() looks at the elements that are selected. Not at its descendants. If you want to select the descendants of <div class="container"> you can do it a number of ways. Here's how to do it with the find(). But this is probably not the most efficient way.

var $contents = $(".container");
$contents.find("*").filter("span");

These are probably more efficient.

$(".container span")
$contents.find("span")

And if you want children, then you can use the following.

$contents.children("span")

There is also the $(descendantsOfElement, element) selector. But I think this one is tough to read though when troubleshooting code, so I rarely, if ever, use it.

Upvotes: 1

wirey00
wirey00

Reputation: 33661

Filter - is used to filter out your results

var $spans = $contents.filter("span"); // <-- filters out the span that are inside $contents collection

So the filter is looking for your $(".container"); elements that are spans

Your filter is equal to

var $spans = $("span.container");

The other ones

var $spans = $(".container span.container"); // <-- gets descendant spans inside .container

So this returns any decendant span elements of $(".container");

So

var $spans = $(".container span") 

Equal to

var $spans = $(".container").find('span');

Equal to

var $spans = $('span',".container");

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

These are equivalent:

$contents.filter("span")
$("span.container");

As both will find elements which are spans with a class of container.

Then, these are equivalent:

$contents.find("span");
$(".container span")

As both will find spans which are contained in an element with a class of container.

Upvotes: 1

Ram
Ram

Reputation: 144689

That's because you are creating a jQuery object which contains a div tag, as there is no selected span element in the set, length is 0.

What you want is find or children method.

Upvotes: 1

Related Questions