Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding newly created dom elements to an empty jQuery object

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!

like image 632
taber Avatar asked May 14 '10 05:05

taber


2 Answers

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
like image 194
Rahen Rangan Avatar answered Oct 19 '22 17:10

Rahen Rangan


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.

like image 40
x1a4 Avatar answered Oct 19 '22 17:10

x1a4