Mixing logical AND and OR in jQuery selector

I need to filter out a list of elements that contain two important data attributes:

<li class="song" data-title="freedom" data-id="7" data-tags="tag-18-eot,tag-2-eot" data-category="1">Freedom</li> 
  • Category
  • Tags

Filtering by categories must be logical OR, but filtering by tags must be logical AND.

Filtering using one of these two problems is not a problem.

I applied for example:

 $(collection).filter('li[data-tags*="tag-50-eot"][data-tags*="tag-51-eot"]'); 

to filter by tags. Or:

 $(collection).filter('[data-category="1"], [data-category="2"]); 

to filter by category.

It works great. However, I could not find a way to combine these two selectors into one query, which I can pass to the filter() function, and a chain of two calls to filter() will not produce the desired result, since the first call can filter out the objects that leave the second call .

I found this question with a similar topic, but the problem is a bit different and the approach.

How can I filter these items correctly?

+8
javascript jquery dom jquery-selectors
source share
2 answers

You should be able to get what you are looking for with a chain if you use the AND condition first. For example:

 var res = $('#collection li') .filter('li[data-tags*="tag-50-eot"][data-tags*="tag-51-eot"]') .filter('[data-category="1"], [data-category="2"]'); 

Fiddle here .

+6
source share

filter function can accept function as input ...

You can get a construct like:

 var set = $(collection).filter( function( index, element ) { return ($(element).attr(...) == "..."); } ); 
-2
source share

All Articles