Linas
Linas

Reputation: 4408

Create jquery object var

I would like to replicate jquery object selection, for example

When i select multiple objects with

var test = $(".someclass");

I get the object with all selected objects with that class.

Now how could i keep adding objects in that war, something like test.push($(".somediv"));

Also i saw .add( jQuery object ) but it gives me error Cannot call method 'add' of null when i try to add object to an empty variable

Also how can i create jquery variable with no values and then add them later?

Upvotes: 0

Views: 3391

Answers (3)

jfriend00
jfriend00

Reputation: 707326

You can use $() to create an empty jQuery object and then you can use .add() to add more items to it via a selector:

var items = $().add(".someClass");
items = items.add(".someDiv");

When using .add(), just remember that it returns a NEW jQuery objects that have the new elements added in. It does not modify the original jQuery object. It's easy to forget that and do:

items.add(".someDiv");

and wonder why nothing is added to items (this has bit me several times).

Upvotes: 6

cosmic_wheels
cosmic_wheels

Reputation: 44

You can do it like this

var objects = $().add(".className").add(".divName");

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

jfriend00 solution is what you'd use with modern version of jQuery. I use this a lot too:

var classes = ['foo', 'bar', 'bla', 'asd'];
var $els = $('.'+ classes.join('.,'));

Upvotes: 1

Related Questions