Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two jQuery Objects

I like to have a return value with one or more jQuery objects to add them to a .

var f = function() {
    var a = $('<div class="a" />');
    // do someting awesome
    return a;
};

Correct example with two s:

var f = function() {
    var ret = $('<div class="a" /><div class="b" />');
    // do something spectecular
    return ret;
};

The problem is that I need these two objects separated inside the function and this is not correct code:

var f = function() {
    var a = $('<div class="a" />'),
        b = $('<div class="b" />'),
        ret = a+b;
    // do something fabulous
    return ret;
}
like image 674
iRaS Avatar asked Mar 28 '13 11:03

iRaS


1 Answers

You can use the jQuery .add() method:

return a.add(b);

From the docs:

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.

like image 62
James Allardice Avatar answered Oct 17 '22 21:10

James Allardice