Reputation: 2549
I'm trying to append some HTML to a div multiple times.
Here's how I'm currently doing it: http://jsfiddle.net/9m1cfL4u/
I want to append it 4 times in total, this method works perfectly fine but is there a tidier way to do this than calling the same append every time? It looks messy and "un-proper" to me!
Thanks for any help!
$('.banner').append('<div class="content"></div>');
$('.banner').append('<div class="content"></div>');
$('.banner').append('<div class="content"></div>');
$('.banner').append('<div class="content"></div>');
Upvotes: 1
Views: 1210
Reputation: 3522
And little bit fancier way of doing same thing.
$.fn.repeatTimes = function(times, cb) {
for(var time = 1;time <= times; time += 1) {
cb.call(this, time);
}
return this;
}
$(function(){
$('.banner').repeatTimes(4, function(time) {
this.append('<div class="content">this is ' + time + ' time</div>');
});
});
<div class="banner"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 240938
A for
loop should suffice.
for (var i = 0; i < 4; i++) {
$('.banner').append('<div class="content"></div>');
}
..and without jQuery:
var banner = document.querySelector('.banner'),
content;
for (var i = 0; i < 4; i++) {
content = document.createElement('div');
content.className += 'content';
banner.appendChild(content);
}
Upvotes: 4