Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
How do I toggle multiple list elements with same class?

I have a list with 5 elements of the same class: "navbar_item". With this code I toggle the 'active' status when clicking the item with the class mentioned, but it only toggles the first element of the list. What do I do to toggle all of them?

const menu = document.querySelector('#mobile-menu');
const menuMenu = document.querySelector('.navbar_menu');
const menuItem = document.querySelector('.navbar_item');

const mobileMenu = () => {
    menu.classList.toggle('is-active');
    menuMenu.classList.toggle('active');
    menuItem.classList.toggle('active');
};

menu.addEventListener('click', mobileMenu);
menuItem.addEventListener('click', mobileMenu);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to use querySelectorAll to get all elements. This provides a list which you can iterate or loop through to both apply eventListeners and toggle classes.

Something like this

const menuItem = document.querySelectorAll('.navbar_item');

const mobileMenu = () => {
    menuItem.forEach( (item) => {
        item.classList.toggle('active');
  })       
};

menuItem.forEach( (item)=> {
    item.addEventListener('click', mobileMenu)
})
.active{
  background-color: lightblue;
}

.navbar_item{
  margin-bottom: 10px;
}
<div class="navbar_menu">
  <div class="navbar_item">Item 1</div>
  <div class="navbar_item">Item 2</div>
  <div class="navbar_item">Item 3</div>
  <div class="navbar_item">Item 4</div>
  <div class="navbar_item">Item 5</div>
</div>

about 4 years ago · Juan Pablo Isaza Report

0

because "querySelector" will only get the first element, if you want to get All; please use "querySelectorAll"; you can also to learn Event delegation to get a better way to solove this problem

const menu = document.querySelector('#mobile-menu');
const menuMenu = document.querySelector('.navbar_menu');
const menuItems = document.querySelectorAll('.navbar_item');

const mobileMenu = () => {
    menu.classList.toggle('is-active');
    menuMenu.classList.toggle('active');
};

menu.addEventListener('click', mobileMenu);
for(let i = 0; i < menuItems.length; i ++) {
  menuItems[i].addEventListener('click', () => {
    menuItem[i].classList.toggle('active');
  });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!