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!

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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 explains why there isn't.
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.

5 Comments

awesome, i thought i tried that too, but apparently not! thanks.
it looks like in order to use .clone(true) on $list, my $list array needs to be a dom node (eg: $('<div />') 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?
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.
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.
and no, you definitely won't need the containing div :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.