javascriptjqueryhtmlloopswhile-loop

While loop and jQuery repeatedly appending not working


I'm trying to make 16 squares side by side using a JavaScript while loop but I don't understand why it doesn't work.

$(document).ready(function() {
  var divs = $("<div class='square'></div>");
  var i = 0;
  while (i < 17) {
    $("#wrapper").append(divs);
    i++;
  }

});
#wrapper {
  width: 600px;
  margin: 70px auto;
}
.square {
  width: 40px;
  height: 40px;
  display: inline-block;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="wrapper">

    <div class="square"></div>

  </div>
</body>

strong text


Solution

  • In the loop, in each iteration you need to create a new object, else it will be just like replacing the same element so many times

    So you can just clone() the element in the loop

    $(document).ready(function() {
      var divs = $("<div class='square'></div>");
      var i = 0;
      while (i < 17) {
        $("#wrapper").append(divs.clone());
        i++;
      }
    
    });
    #wrapper {
      width: 600px;
      margin: 70px auto;
    }
    .square {
      width: 40px;
      height: 40px;
      display: inline-block;
      border: 1px solid black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="wrapper">
    
      <div class="square"></div>
    
    </div>