1

I'm trying to create 5 divs inside another 5 divs using loop in javascript. I have made the main divs but all small divs are created only in one main div and only three small divs are created. How to make one small div for one main div? The same thing must repeat 5 times.

for(let n=0; n<5; n++){
  var elm = document.createElement('div');
  elm.id="comments";
  document.getElementById('elm').appendChild(elm);

  var sec = document.createElement('div');
  sec.id = "sec";
  document.getElementById('comments').appendChild(sec);
}
#elm{
  width: 90vw;
  height: 90vh;
  background: blue;
 }
#comments{
  background: brown;
  width: 100%;
  height: 150px;
  border: 2px solid yellow;
 }
#sec{
  width: 50px;
  height: 50px;
  background: chartreuse;
  z-index: 1000;
  border: 2px solid darkgreen;
 }
<div id="elm"></div>

1
  • 1
    Ids have to be unqiue. Commented Apr 18, 2020 at 11:43

1 Answer 1

2

The attribute id must be unique in a document, use class instead. Also, you should append the sec element inside the currently created comments element in each iteration:

for(let n=0; n<5; n++){
  var elm = document.createElement('div');
  elm.setAttribute('class',"comments");
  document.getElementById('elm').appendChild(elm);

  var sec = document.createElement('div');
  sec.setAttribute('class', "sec");
  elm.appendChild(sec); // append the sec element inside the current comments element
}
#elm{
  width: 90vw;
  height: 90vh;
  background: blue;
}
.comments{
  background: brown;
  width: 100%;
  height: 150px;
  border: 2px solid yellow;
}
.sec{
  width: 50px;
  height: 50px;
  background: chartreuse;
  z-index: 1000;
  border: 2px solid darkgreen;
}
<div id="elm"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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