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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With