How to combine two jQuery results

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

You can use add();

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

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

or

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

Solution 2 - Jquery

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnickfView Question on Stackoverflow
Solution 1 - JquerySimonView Answer on Stackoverflow
Solution 2 - JqueryDylan KasView Answer on Stackoverflow