Reputation: 5840
I have to filter a list of items, that contain two crucial data attributes:
<li class="song" data-title="freedom" data-id="7" data-tags="tag-18-eot,tag-2-eot" data-category="1">Freedom</li>
Filtering by category should be by logical OR but filtering by tags should be by logical AND.
Filtering using one of these two 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.
This works fine. However, i could not find a way to combine these two selectors into one single query that i can pass to the filter()
function, and chaining two filter()
calls does not lead to the desired result, because the first call might filter out items that the second call would leave behind.
I found this question with a similar topic, but the problem is a little different and the approach as well.
How can I filter those items correctly?
Upvotes: 10
Views: 828
Reputation: 1890
the filter function can receive a function as input...
You may end up with a construct like:
var set = $(collection).filter(
function( index, element )
{
return ($(element).attr(...) == "...");
}
);
Upvotes: -2
Reputation: 33151
You should be able to get what you are looking for with chaining, as long as 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.
Upvotes: 8