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