Richard Carter
Richard Carter

Reputation: 71

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.

Upvotes: 7

Views: 7296

Answers (5)

Vatsal Pathak
Vatsal Pathak

Reputation: 68

$(document).ready(function() {
    star = '<div class="star" />';
    var body = $('body');

    for ( i = 0; i < 12; i++ ) {
        body.append($(star));
    }
});
.star {  border: 1px solid black; height: 20px; width: 100px;margin-bottom:1px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Upvotes: 0

em2
em2

Reputation: 93

It should be noted that using FOR loop is worse than iterating with jquery .each() function, as FOR loop is not asynchronous and therefore much much slower on bigger scale, since each() instances run side by side, when FOR loop waits for each iteration to complete before continueing to next iteration.

(Can't just comment because of 50 rep requirement.)

Upvotes: 0

kobe
kobe

Reputation: 15835

Try this

var star = '<div class="star" />SomeTest</div>';

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

Upvotes: 2

Sebastian Otto
Sebastian Otto

Reputation: 15279

$('body').append(new Array(13).join('<div class="star" />'));

Upvotes: 3

Jon Gauthier
Jon Gauthier

Reputation: 25572

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

Upvotes: 15

Related Questions