Search code examples
jquerycss-selectorsselfdescendant

Descendent or self selector in jQuery


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?


Solution

  • 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 :-)