0

I am trying to generate a row of 16 boxes on load of webpage.

Here is my code:

var box = $("<div></div>").addClass("box");
    $(document).ready(function(){
            for(var i = 0; i < 16; i++) {
                $("#container").append(box);
                }
            });

I also tried this within the for loop's code block:

if($("#container:contains(box)")) {
   $(box).append(box);
}

I kind of understand why this does not work. That var box is only referencing an element and is not a copy of an element?

As you can likely tell, I'm new. I would really appreciate some pointers on how I can achieve this. Thanks.

1
  • $("#container").append(box.clone()); would work. More efficient doing this as string though Commented Jan 24, 2015 at 23:34

3 Answers 3

2

Why not just use like this?

for(var i = 0; i < 16; i++) {
   $("#container").append('<div class="box box-'+i+'" />');
}
Sign up to request clarification or add additional context in comments.

1 Comment

That will leave strange attributes: <div class="box box-"0 />, etc. You probably meant `$("#container").append('<div class="box box-' + i + '" />');
0

You're appending the same div over and over. That will just move it (in this case, right back where it was). For a new div each time:

$(document).ready(function(){
  var ctr = $('#container');

  for(var i = 0; i < 16; i++) {
    ctr.append("<div class='box'></div>");
  }
});

  $(document).ready(function() {
    var ctr = $('#container');

    for (var i = 0; i < 16; i++) {
      ctr.append("<div class='box'></div>");
    }
  });
.box {
  margin: 10px;
  height: 25px;
  width: 25px;
  background-color: red;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>

1 Comment

Seems so simple now that you have shown me how, ha! Thank you Paul.
0

I recommend against using append in a loop, bad performance. I suggest this:

  var buffer = [];

  for(var i = 0; i < 16; i++) {
    buffer.push("<div class='box'></div>");
  }

  var html=buffer.join('');
  $('#container').append(html);

1 Comment

I'll have a play about with this method also. Thanks.

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.