SquareCat SquareCat - 1 month ago 8
Javascript Question

Mixing logical AND and OR in jquery selector

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>

  1. Category

  2. Tags

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:


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
function, and chaining two
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?


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('[data-category="1"], [data-category="2"]'); 

Fiddle here.