3

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.

3
  • 2
    Isn't that what .each() does? Commented Jun 6, 2013 at 4:35
  • the each in jQuery is implicit, and I would like to merge the objects together. Commented Jun 6, 2013 at 4:36
  • $.each([$object1,$object2], function(index, val) { val.myFunction(); }); Commented Jun 6, 2013 at 4:47

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

4 Comments

I don't understand the odd looking of this method: what if I do: var $one_and_two = $($object1).add($object2); ?
@mimo: That should work pretty much the same.
"Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method." There is no need to create a new empty jQuery object.
@JanDvorak: Right, thanks for the reminder. For some reason I though $x.add(...) modified $x.
-1

You can use jQuery.merge to merge the element cache together, because they are essentially arrays.

jQuery.merge($object1, $object2).myFunction(); 

Do note that $object1 will contain the merged list, so you will not be able to re-use the cache. You can avoid that by:

$.merge( $.merge([], $object1), $object2); 

IMO, I think it would be simpler to do this:

function assignHandler () { $object1.myFunction(); $object2.myFunction(); } 

2 Comments

Description: Merge the contents of two arrays together into the first array.
$.merge: Returns: Array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.