How do you toggle the classList of menu items separately with JavaScript?

I have a footer with several dropdown items. I want to toggle the "active" classList specifically for the element that was clicked. So far my code is:

I have multiple containers like this:

let dropDowns = document.querySelectorAll('.footer-arrow-container')
let dropDownList = document.querySelector('.footer-items-list')

dropDowns.forEach((dropDown) => {
  dropDown.addEventListener('click', () => {
    dropDownList.closest('ul').classList.toggle('active')
  })
})
.footer-items-list {
  display: none;
}

.active {
  display: flex;
}
<div class="footer-item-container">
  <div class="footer-arrow-container">
    <!-- dropDowns ; querySelectorAll -->
    <h2 class="footer-item-title">
      Test
    </h2>
    <img/>
  </div>
  <div class="footer-dropdown-list-container">
    <ul class="footer-items-list">
      <!-- dropDownList : querySelector -->
      <li>List item 1</li>
      <li>List item 2</li>
    </ul>
  </div>
</div>

Currently, this is only selecting the "ul" from the first list. It doesn’t work for the other lists individually so I’m clearly selecting it incorrectly in the JavaScript and I’m not sure the best way to do this.

>Solution :

The HTML structure is unclear. I’ve taken you at your word, that each footer item has the same structure, and placed two in this example. Basically, the code goes up to the common ancestor, then down to the child.

let dropDowns = document.querySelectorAll('.footer-arrow-container')

dropDowns.forEach((dropDown) => {
  dropDown.addEventListener('click', () => {
    dropDown.closest('.footer-item-container').querySelector('.footer-items-list').classList.toggle('active')
  })
})
.footer-items-list {
  display: none;
}

.active {
  display: flex;
}
<div class="footer-item-container">
  <div class="footer-arrow-container">
    <!-- dropDowns ; querySelectorAll -->
    <h2 class="footer-item-title">
      Test
    </h2>
    <img/>
  </div>
  <div class="footer-dropdown-list-container">
    <ul class="footer-items-list">
      <!-- dropDownList : querySelector -->
      <li>List item 1</li>
      <li>List item 2</li>
    </ul>
  </div>
</div>
<div class="footer-item-container">
  <div class="footer-arrow-container">
    <!-- dropDowns ; querySelectorAll -->
    <h2 class="footer-item-title">
      Test 2
    </h2>
    <img/>
  </div>
  <div class="footer-dropdown-list-container">
    <ul class="footer-items-list">
      <!-- dropDownList : querySelector -->
      <li>List item 3</li>
      <li>List item 4</li>
    </ul>
  </div>
</div>

Leave a Reply