Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the intersection of two jquery objects

Tags:

jquery

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 these:

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

How do I merge these two selectors into one where BOTH references are true? I want to end up with a selector that only contains div's 1 and 3 but using the already existing $cats and $features - not build another selector based on markup

like image 780
gpcola Avatar asked Sep 23 '13 18:09

gpcola


2 Answers

$.fn.intersect=function(jq){
  return $(this).filter(jq);
}

Then :

$cats.intersect($features);
like image 130
Abdennour TOUMI Avatar answered Sep 17 '22 15:09

Abdennour TOUMI


Union:

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

This will get all divs where either the [data-category] attribute is mycategory or the [data-features] attribute is myfeature.

This can be done with multiple selectors as $one.add($two)

Intersection:

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

This will get all divs where both the [data-category] attribute is mycategory and the [data-features] attribute is myfeature.

This can be done with multiple selectors as $one.filter($two)

like image 24
zzzzBov Avatar answered Sep 21 '22 15:09

zzzzBov