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