brentonstrine
brentonstrine

Reputation: 22742

Why is this only appended once?

This loop (see jsfiddle) tries to append a <span> tag to a container five times. But it only does it once. Why?

var myArr = [0,1,2,3,4];
var $span= $('<span></span>');
for (var i = 0; i < (myArr.length); i++) {
    $('.contain').append($span);
}

Upvotes: 5

Views: 86

Answers (1)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

The problem is that you're appending the same element multiple times.
Use clone to clone the element and then append.

$('.contain').append($span.clone());

demo

Update:

This way you can customize your element and then clone it with all properties.

var $span = $('<span/>', {
                    'class': 'someClass otherClass',
                    'css': {
                         'background-color': '#FF0000'
                     }
            });
for (var i = 0; i < (myArr.length); i++) {
    $('.contain').append($span.clone());
}

demo2

Update2: according to this comment.

$('.contain').append('<span class="yourClass"/>');

Upvotes: 7

Related Questions