views:

36

answers:

3

I want to search for all elements with class needle in all elements returned by jQuery('.haystack') and have tried jQuery('.haystack .needle'), but this doesn't seem to pick up the case where an element has both classes. Is there a selector that will do this?

A: 
$('.haystack').find('.needle');

Kind Regards

--Andy

jAndy
A: 

You do this with no space in there, like this:

jQuery('.haystack.needle')

The alternative is:

jQuery('.haystack').filter('.needle')

With the space it's looking for children of those .haystack elements with .needle, without the space, you're matching the same elements, but saying they must have both classes to match now. This is also what .filter() does, it further cuts down the matches set to those elements also matching the selector you pass into it.

Nick Craver
+4  A: 

Try combining selectors:

jQuery('.haystack.needle, .haystack .needle');

This will select all .haystacks that are also .needles and any .needle which is a descendant of a .haystack, which I think is exactly what you asked for :-)

Andy E