Descendant selector or on its own in jQuery

I want to search for all elements with the needle class in all elements returned by jQuery('.haystack') and tried jQuery('.haystack .needle') , but this does not seem to be suitable for the case when the element has both classes. Is there a selector that will do this?

+4
source share
2 answers

Try combining selectors :

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

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

+5
source

You do this without spaces, for example:

 jQuery('.haystack.needle') 

Alternative option:

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

With the space in which he searches for children from these .haystack elements with .needle , without space you map the same elements, but saying that they must have both classes to match. It also means .filter() , it also reduces the matches set for these elements, also corresponding to the selector that you pass to it.

+1
source

Source: https://habr.com/ru/post/1306456/


All Articles