Reputation: 22742
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
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());
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());
}
Update2: according to this comment.
$('.contain').append('<span class="yourClass"/>');
Upvotes: 7