Radley Sustaire
Radley Sustaire

Reputation: 3399

Combine jquery variables into one selector?

I'm looking for a way to combine jquery variables. Looking through related questions, nobody seems to be trying what I want to do.

$("body, div, p") is one method of combining by selectors, but after you assign a selector to a variable, how do you combine them in a similar fashion?

Here is one method I tried, but did not get it to work. I also tried putting them into an array (by simply adding brackets before $body and after $p).

$body = $("body");
$div = $("div");
$p = $("p");
$mixed = $($body, $div, $p);
// $mixed = $("body, div, p"); is NOT what I am looking for

In my actual script I've got some <select> inputs assigned to variables. I would like to put them into groups, so say I have a <select> which has "FRUIT" and another one that has "VEGETABLES", I could put them both into a jquery variable called "PRODUCE". Then if I need to perform anything on both of the two, I use produce instead.

...This might just be a stupid way to do things, though.

Upvotes: 23

Views: 10666

Answers (3)

acjay
acjay

Reputation: 36691

For me, it works fine in jQuery 1.10.2 to simply combine the elements in an array literal before passing into the jQuery constructor: $mixed = $([$body, $div, $p]);

Upvotes: 2

Youngs
Youngs

Reputation: 147

I too was looking for something like this. In my case I had some objects passed into a common function and some created in memory and I wanted to apply the same click event to all of the objects. In the end I went with James's add solution above but thought I would share another option.

If you put the objects into an array you can use the each iterator to perform an action on them.

[$body, $div, $p].each(function(i,e) { e.DoSomething(); });

This syntax is longer and you don't get a reusable $mixed object, but there may be some scenarios where this is useful.

Upvotes: 0

James M
James M

Reputation: 16728

Perhaps you're looking for .add()?

$mixed = $body.add($div).add($p);

Upvotes: 45

Related Questions