iRaS
iRaS

Reputation: 2136

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

Upvotes: 5

Views: 4648

Answers (3)

Anderson Souza
Anderson Souza

Reputation: 1

Check this out:

var $bindDivs = $.merge( $( '#div1' ), $( '#div2' ) );

Upvotes: 0

iRaS
iRaS

Reputation: 2136

I just found a solution for my own question:

var f = function() {
    var a = $('<div class="a" />'),
        b = $('<div class="b" />'),
        ret = $.extend({}, a);
    ret.push(b[0]);
    // do something fabulous
    return ret;
}

Maybe you have better solutions? It doesn't look very well you know.

Upvotes: 0

James Allardice
James Allardice

Reputation: 166061

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.

Upvotes: 13

Related Questions