Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

$(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?

like image 273
SquareCat Avatar asked Sep 04 '16 09:09

SquareCat


People also ask

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

Which is the fastest selector in jQuery?

ID Selector: The jQuery #id selector selects the element on the basis of the ID attribute of the HTML tag. This selector is basically used when we have to work on a single element because an ID should be unique within a web page.

What does $$ mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

What does $() return in jQuery?

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.


1 Answers

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.

like image 83
Matt Way Avatar answered Oct 03 '22 08:10

Matt Way