1

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

2 Answers 2

4

A for loop should suffice.

Updated Example

for (var i = 0; i < 4; i++) {
    $('.banner').append('<div class="content"></div>');
}

..and without jQuery:

Example Here

var banner = document.querySelector('.banner'),
    content;

for (var i = 0; i < 4; i++) {
    content = document.createElement('div');
    content.className += 'content';
    banner.appendChild(content);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.