6

Why doesn't this work in jQuery 1.4.2?


var $list = $([]);
for(var i=0; i<50; i++) {
    $list.add( $('<div/>', { id: 'jake', class: 'test' }).data('test', { hi: 'hello' }) );
}
alert($list.size()); // 0

Thanks!

taber
  • 3,166
  • 4
  • 46
  • 72
  • Correct explanation given at : [jQuery add elements to empty selection?][1] [1]: http://stackoverflow.com/questions/7533929/jquery-add-elements-to-empty-selection – mohanrajt Apr 18 '13 at 07:00

2 Answers2

11

Pointing back the reference list again works for me; e.g. $list = $list.add( $('<div/>') );

var $list = $([]);
for(var i=0; i<50; i++) {
    $list=$list.add( $('<div/>', { 'id': 'jake'+i, 'class': 'test' }).data('test', { hi: 'hello' }) );
}
alert($list.size()); // 50
Rahen Rangan
  • 715
  • 5
  • 8
  • Upvote for solving my problem, but I wish there was a better way (read: `.append()`) to add items to an empty set. Shog9's answer to a [similar question](http://stackoverflow.com/questions/5598494/how-to-create-an-empty-non-null-jquery-object-ready-for-appending) explains why there isn't. – Michael Jun 26 '12 at 14:52
4

Why add doesn't work I don't know, but you can replace it with push due to jQuery being an Array-like object, which should do what you want.

x1a4
  • 19,417
  • 5
  • 40
  • 40
  • awesome, i thought i tried that too, but apparently not! thanks. – taber May 14 '10 at 05:36
  • it looks like in order to use .clone(true) on $list, my $list array needs to be a dom node (eg: $('
    ') but i don't want a containing div, i just want a list of dom nodes with no parent. (like an array!) is that possible?
    – taber May 14 '10 at 05:41
  • it's not the end of the world if i have to have a containing div i guess. it's just extra junk in the dom. oh well. – taber May 14 '10 at 05:51
  • In your case, because each div is created separately before being pushed onto $list, each element in $list is actually its own separate jQuery object, so THOSE are what you need to call clone on: `clones = $list.map(function () { return this.clone(true); });` and you should be good to go. – x1a4 May 14 '10 at 05:52
  • and no, you definitely won't need the containing div :) – x1a4 May 14 '10 at 05:53