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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With