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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With