Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply the same function to multiple jQuery objects without reselct them [duplicate]

I use to declare all the objects I need at the top of my functions, which I use to cache and keep the app fast. For example I have something like:

var $object1 = $('#my_element'),
    $object2 = $('.other_elements'),
    $object3 = $('.again_something_else');

I use those variables in the code individually, so for example $object1.doSomething() or $object2.doElse() but in some scenarios I need to apply the same function to two or more already selected variables. There is a way to merge those variables together, to avoid re-selecting of the elements I need?

I would avoid this:

 $('#my_element, .other_elements').myFunction()

and reuse the variables I have already.

like image 812
Mimo Avatar asked Sep 02 '26 05:09

Mimo


1 Answers

You could use add:

Description: Add elements to the set of matched elements.

So if you wanted to combine $object1 and $object2, you could:

var $one_and_two = $object1.add($object2);

Demo: http://jsfiddle.net/ambiguous/DHJvR/1/

add doesn't modify anything, it simply merges the selected elements into a new jQuery object and returns it so $x.add(...) won't do anything to $object1 (thanks to Jan Dvorak for the reminder/correction on this point).

like image 134
mu is too short Avatar answered Sep 03 '26 19:09

mu is too short