Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 330
Radley Sustaire Avatar asked Jan 29 '12 20:01

Radley Sustaire


2 Answers

Perhaps you're looking for .add()?

$mixed = $body.add($div).add($p);
like image 78
James McLaughlin Avatar answered Oct 18 '22 00:10

James McLaughlin


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

like image 24
acjay Avatar answered Oct 18 '22 02:10

acjay