Toggle dropdown for each box with JS

I would like to toggle the dropdown for the each of these boxes, but for some reason only the first one gets visible:

const button = document.querySelector("button");
const dropdown = document.querySelector(".dropdown");

button.addEventListener("click", () => {
  dropdown.classList.toggle("dropdown-visible");
})
.box {  
  height: 100px;
  width: 300px;
  position: relative;
}

.dropdown {
  height: 100px;
  width: 100%;
  position: absolute;
  background: red;
  top: 100%;
  right: 0;
  display: none;
}

.dropdown-visible {
  display: block;
}
<div class="box">
  box 1
  <button>toggle</button>
  <div class="dropdown">dropdown content</div>
</div>
<div class="box">
  box 2
  <button>toggle</button>
  <div class="dropdown">dropdown content</div>
</div>
<div class="box">
  box 3
  <button>toggle</button>
  <div class="dropdown">dropdown content</div>
</div>

I guess I should loop through these, but when I tried the querySelectorAll, it did not work..

14 thoughts on “Toggle dropdown for each box with JS”

Leave a Comment