0

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?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Linas
  • 4,380
  • 17
  • 69
  • 117
  • possible duplicate of [Getting an empty JQuery object](http://stackoverflow.com/questions/897331/getting-an-empty-jquery-object) -- and you already know `.add` as far as I can tell. – Felix Kling Aug 10 '12 at 23:15
  • Better duplicate: [jQuery add elements to empty selection?](http://stackoverflow.com/questions/7533929/jquery-add-elements-to-empty-selection). – Felix Kling Aug 10 '12 at 23:22

3 Answers3

6

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Ah, that explains it, then. I saw that you'd (re-) edited to add new stuff, but hadn't realised that the omission of the quote was caused by an edit-race (for want of a better word). Just wondered if you knew something (else...) that I didn't. =) – David Thomas Aug 10 '12 at 23:20
1

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('.,'));
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • That's not adding elements though, it's selecting all of them at once. – Felix Kling Aug 10 '12 at 23:21
  • **@Felix Kling** I don't think it makes a difference, it depends on the situation tho. If you already have an object you can always do this `$el.add('.'+ classes.join('.,'))` and it would be the same as adding four times. – elclanrs Aug 10 '12 at 23:24
0

You can do it like this

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