How to individually toggle a menu item's classList using JavaScript?
P粉949848849
P粉949848849 2024-02-17 17:22:12
0
1
352

I have several dropdown items in my footer. I want to toggle the "active" class list specifically for the clicked element. My code so far 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>

<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 just selects "ul" from the first list. It doesn't work with separate other lists, so I've obviously chosen it wrong in JavaScript, and I'm not sure the best way to do this.

P粉949848849
P粉949848849

reply all(1)
P粉510127741

HTML structure is unclear. I take your word for it that every footer item has the same structure and placed two in this example. Basically, the code goes up to the common ancestor and then down to the children.

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;
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template