How to show and hide dropdowns using for of loop?

I have created three custom dropdowns using same classes. I need to open them one at the time, but when I click on one I open all of them.

 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="service-tab_content--open">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="service-tab_content--open">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="open-dropdown">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

Javascript

const dropdowns = document.querySelectorAll(".dropdown");
const dropdownList = document.querySelectorAll(".open-dropdown");

for (const drop of dropdowns) {
  drop.addEventListener("click", () => {
    for (const list of dropdownList) {
      list.classList.toggle("open-list");
    }
  });
}

How can I track witch dropdown is clicked? I don’t want to close one with opening another, just open current one clicked.

Class open-list is just here to add display: block to my hidden list.

>Solution :

const dropdowns = document.querySelectorAll(".dropdown");
const dropdownList = document.querySelectorAll(".open-dropdown");

for (const drop of dropdowns) {
  drop.addEventListener("click", (evt) => {
    evt.currentTarget.nextElementSibling.classList.toggle('open-list');
  });
}
ul {
  display: none;
}

ul.open-list {
  display: block;
}
 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="service-tab_content--open">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="service-tab_content--open">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

 <div class="dropdown">
    <p>Open dropdown</p>         
  </div>
  <ul class="open-dropdown">
      <li>Data 1</li>
      <li>Data 2</li>
      <li>Data 3</li>
      <li>Data 4</li>
      <li>Data 5</li>
   </ul>

Leave a Reply