How to get the intersection of two jquery objects

I have a number of elements with the following markup:

<div id="div1" data-category="mycategory" data-feature="myfeature"></div> <div id="div2" data-category="anothercategory" data-feature="myfeature"></div> <div id="div3" data-category="mycategory" data-feature="myfeature"></div> <div id="div4" data-category="mycategory" data-feature="anotherfeature"></div> 

And two jQuery selectors that reference them:

 $cats = $('div[data-category="mycategory"]'); $features = $('div[data-features="myfeature"]'); 

How to combine these two selectors into one, where the BOTH links are correct? I want to end up with a selector that only contains divs 1 and 3, but using the already existing $ cats and $ features - do not create another selector based on markup

+7
jquery
source share
2 answers

Union:

 $('div[data-category="mycategory"], div[data-features="myfeature"]')... 

This will get the whole div, where either the [data-category] attribute mycategory or the [data-features] myfeature .

This can be done with a few selectors like $one.add($two)

Intersections:

 $('div[data-category="mycategory"][data-features="myfeature"]')... 

This will get the whole div, where both the [data-category] attribute is mycategory and the [data-features] myfeature .

This can be done with a few selectors like $one.filter($two)

+13
source share
 $.fn.intersect=function(jq){ return $(this).filter(jq); } 

Then:

 $cats.intersect($features); 
+2
source share

All Articles