Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this only appended once?

Tags:

jquery

append

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);
}
like image 663
brentonstrine Avatar asked Oct 10 '12 00:10

brentonstrine


1 Answers

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"/>');

like image 142
Ricardo Alvaro Lohmann Avatar answered Nov 06 '22 04:11

Ricardo Alvaro Lohmann