167

How do you combine two jQuery search results? eg:

var $allFoos = $('.foo'),
    $allBars = $('.bar')
    $allFoosAndBars = $allFoos + $allBars;

Obviously, I just made up that last line, but I hope it makes it sorta clear what I mean. To be clear, the example is greatly simplified, and it could be any arbitrary sets i'm talking about, so $('.foo, .bar') is not what I'm after.

Zze
  • 18,229
  • 13
  • 85
  • 118
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 1
    possible duplicate of [Merging jQuery objects](http://stackoverflow.com/questions/1881716/merging-jquery-objects) – Gajus Apr 06 '14 at 15:10

2 Answers2

239

You can use add();

var $foos = $('.foo');

var $foosAndBars = $foos.add('.bar');

or

var $allFoosAndBars = $allFoos.add($allBars);
James Cushing
  • 718
  • 1
  • 9
  • 18
Simon
  • 37,815
  • 2
  • 34
  • 27
  • 30
    Note that in the line "$all.add('.bar');", variable $all is not changed and thus, does not hold all elements. You would need to assign the return value again like "$all = $all.add('.bar');". – Wolfram Jan 10 '11 at 14:58
  • 20
    If you want to make it more apparent that you are combining the two and not adding one set to the other (as the name implies) you can to this: `var $allFoosAndBars = $().add($allFoos).add($allBars);` – Chris Bloom Apr 26 '12 at 17:01
  • 13
    The method should have been called "and" instead of "add" -- would be more intuitive. – Faust Nov 07 '14 at 21:27
  • 1
    @Faust For those familiar with set operations, AND and UNION are very different. – ricksmt Jul 15 '15 at 18:03
  • 1
    Why is $.merge() not mentioned here? – Ondra Žižka Nov 30 '15 at 20:25
  • If you want to combine more than two result sets: `function combine() { var i; var combined = $(); for (i = 0; i < arguments.length; i++) { combined = combined.add(arguments[i]); } return combined; }` – Justin Fiedler Dec 22 '17 at 23:59
6

Another solution is to use jQuery.merge() (jQuery > 1.0)

Description: Merge the contents of two arrays together into the first array.

So you could simply use it to merge both result :

var $allFoos = $('.foo');
var $allBars = $('.bar');

var $allFoosAndBars = $.merge($allFoos, $allBars);
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • Be aware that `$.merge` is destructive, so `$allBars` would be merged into `$allFoos` as well as returned in `$allFoosAndBars`... which is probably not what you want – freefaller Dec 08 '22 at 14:40