Skip to content Skip to sidebar Skip to footer

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 s

Solution 1:

Perhaps you're looking for .add()?

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

Solution 2:

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

Solution 3:

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.

Post a Comment for "Combine Jquery Variables Into One Selector?"