Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append an element more than once

I'm currently trying to add n number of divs to the bottom of the body, however using this code:

star = $('<div class="star" />');

for(i=0; i<12; i++) {
    $('body').append(star); 
}

results in just one div being appended to the bottom of the body. I'm guessing this is because the content of the body is not being refreshed between each iteration of the for loop, but can't figure out how to best to solve it.

like image 356
Richard Carter Avatar asked Jul 09 '11 16:07

Richard Carter


1 Answers

Rather than executing 12 DOM modifications, why not multiply the string and then use just one .append() call?

String.prototype.times = function(n) {
    return Array.prototype.join.call({length: n+1}, this);
};

var star = '<div class="star" />'.times(12);
$('body').append(star);

jsFiddle


Fix for your original method

If you want to stay with your method, you'll need to call the $ function inside the loop so that a distinct jQuery object is created on each iteration. I'm guessing this is slower, but it'd work.

star = '<div class="star" />';
var body = $('body');

for ( i = 0; i < 12; i++ ) {
    body.append($(star));
}

jsFiddle

like image 112
Jon Gauthier Avatar answered Sep 19 '22 10:09

Jon Gauthier