Lukas Lukas - 15 days ago 6
Javascript Question

Generate 3000 squares procedurally

I need to build a widget that contains 3000 squares. Doing this manually would take a very long time, maybe some of you know the easiest way to generate the class .square 3000 times? I need also be able to alter the content of each square, for example a color, title, etc. Thx friends!

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


https://jsfiddle.net/srowf8hg/

Answer

You just need a loop and create a new square on each iteration. In order to be able to access each square individually, each generated square gets its own unique id:

var cont = document.getElementById("container");

for(var i = 1; i <3001; ++i){
 var div = document.createElement("div");
 div.setAttribute("class", "square");
 div.setAttribute("id", "div" + i);
 
 var h1 = document.createElement("h1");
   h1.textContent = i;
   div.appendChild(h1);
   cont.appendChild(div);
 }
.square{
  background:#fa5339;
  color:#fff;
  width:100px;
  height:100px;
  float:left;
  border:1px solid #d63d26;
}
h1{
    height: 50%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}
<div id=container>
  
</div>

Comments