0

I have two distinct jQuery objects, one from a selector query and one created from html code. Now I want to make another jQuery object out of these to do operations on both of them.

As you can see here (http://jsfiddle.net/D799Y/), it is possible to do this by using the "get" operation and building an array of elements:

var $first = $('div.first'),
    $overlay = $('<div class="overlay" />'),
    $list;

$first.before($overlay);

// build list out of elements
$list = $([ $first.get(0), $overlay.get(0) ]);

// modify the list
$list.css('border', '2px solid green');

Is there a way to do make $list directly out of the two jQuery objects? Can you add a jQuery object to another one?

This would also be more interesting if f.i. $first would contain more than one elements.

BTW, I know of this possibility, but it's so unsatisfactory. :)

$list = $(".first,.pane");
0

3 Answers 3

5

You can simply use the add() method:

$list = $first.add($overlay);

Note that add() is non-destructive: it creates a new jQuery object instead of modifying the one it is called on, which is what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is so simple that I don't know how I could have overlooked it in the docs.
2

You can use .add()

$list = $first.add($overlay);

Comments

1

You can add elements to the set of matched elements using .add() method like:

// build list out of elements
$list = $first.add($overlay);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.