Display div element in forloop using querySelectorAll

Use a class since Ids have to be unique. Add click event listener, show the child inside.

const boxes = document.querySelectorAll(".box");
for (var i = 0; i < boxes.length; i++) {
  boxes[i].addEventListener("click", function () {
    this.children[0].classList.toggle("active");
  });
}
.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: inline-block;
}

.box > div {
  width: 100%;
  height: 100%;
  display: none;
}

.box > div.active {
  display: block;
}

.red-box {
  background-color: red;  
}

.green-box {
  background-color: green;  
}

.blue-box {
  background-color: blue;  
}
<div class="box">
  <div class="red-box"></div>
</div>
<div class="box">
  <div class="green-box"></div>
</div>
<div class="box">
  <div class="blue-box"></div>
</div>

And without JavaScript

.selector {
  display: none;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: inline-block;
}

.box > div {
  width: 100%;
  height: 100%;
  display: none;
}

.selector:checked + .box > div {
  display: block;
}

.red-box {
  background-color: red;  
}

.green-box {
  background-color: green;  
}

.blue-box {
  background-color: blue;  
}
<input type="checkbox" id="box1" class="selector">
<label for="box1" class="box">
  <div class="red-box"></div>
</label>
<input type="checkbox" id="box2" class="selector">
<label for="box2" class="box">
  <div class="green-box"></div>
</label>
<input type="checkbox" id="box3" class="selector">
<label for="box3" class="box">
  <div class="blue-box"></div>
</label>

<hr/>

<input type="radio" name="color" id="box1r" class="selector">
<label for="box1r" class="box">
  <div class="red-box"></div>
</label>
<input type="radio" name="color" id="box2r" class="selector">
<label for="box2r" class="box">
  <div class="green-box"></div>
</label>
<input type="radio" name="color" id="box3r" class="selector">
<label for="box3r" class="box">
  <div class="blue-box"></div>
</label>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top