Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jQuery objects to the jQuery composite object

Simply put: the jQuery object is a composite pattern. How do I add jQuery objects to it?

An example:

var e1 = $('#element1');
var e2 = $('#element2');

...

I know want to create a new jQuery object jq such that it is composed of e1 and e2. I want to be able to do something like the following:

var jq = $();
jq.addInjQueryObjects([e1, e2]);
jq.hide();

how do I do this?

By the way, I realize that I could have just selected #element1 AND #element2 to begin with, that's not what I'm talking about.

like image 401
George Mauer Avatar asked Oct 17 '10 18:10

George Mauer


1 Answers

You can use jQuery's .add() method:

var e1 = $('#element1');
var e2 = $('#element2');

var jq = $();
jq = jq.add(e1).add(e2);
jq.hide();

It returns a new jQuery object instead of modifying the original, so you need to overwrite the original if you want to reuse the same variable.


EDIT: Note that you can also use jQuery.merge(), which will modify the original, but you'll need to pass in an Array of the DOM elements instead of the jQuery objects.

var e1 = $('#element1');
var e2 = $('#element2');

var jq = $();
$.merge( jq, [e1[0], e2[0]] );
jq.hide();
​
like image 166
user113716 Avatar answered Oct 13 '22 23:10

user113716