tags:

views:

639

answers:

2

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.

A: 

UPDATE: (Ignore the first half; It's wrong)

 var $allFoosAndBars = $allFoos.Append($allBars);

Also, though you said you didn't want it, a variation would is workable:

var $Foos = '.foo', $Bars = '.bar', $allFoosAndBars = $($Foo +", "+$Bars);
James Curran
Append will physically restructure the DOM rather than just increase the selection
Simon
+8  A: 

You can use add();

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

$all.add('.bar');

or

var $allFoosAndBars = $allFoos.add($allBars);
Simon
i'm just adding an extra way to use it into your code sample - i hope you don't mind.
nickf
Not at all - I should have included that myself
Simon
Note: If $allFoos is a zero length result, you can't perform the .add() function to combine it with $allBars. So code a conditional: If $allFoos.length == 0 then assign $allFoosAndBars = $allBars.
micahwittman