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

144
Views
Adding active class to element on menu

I'm looking to add an active element class to my navbar, when I select the next link the previous one stays highlighted, I just want the current link to remain active.

See code below:

 <header>
  <nav>
    <ul>
      <li><a href="#">home</a></li>
      <li><a href="#">about</a></li>
      <li><a href="#">service</a></li>
      <li><a href="#">profile</a></li>
      <li><a href="#">portfolio</a></li>
      <li><a href="#">contact</a></li>
    </ul>
  </nav>
</header>

    
document.querySelectorAll('li').forEach(item => {
  item.addEventListener('click', event => {
    alert(item.outerHTML);
    if(item.className === "active"){
    item.classList.remove("active");
    }
    item.classList.add("active");

  });

})

https://jsfiddle.net/9xca1pgh/42/

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could remove active class from all li element and add the active class to the current one

document.querySelectorAll('li').forEach(item => {
  item.addEventListener('click', event => {
    document.querySelectorAll('li').forEach(i => {i.classList.remove('active')})
    item.classList.add('active')
  })
})

If you want to use for loops

for(let item of document.querySelectorAll('li')) {
  item.addEventListener('click', event => {
    // Remove active class from all li
    for(let i of document.querySelectorAll('li')) {
      i.classList.remove('active')
    }
    item.classList.add('active')
  })
}
about 4 years ago · Juan Pablo Isaza Report

0

because the item in the event is target to this

  • itself, you need to find the active tag and remove it.

    document.querySelectorAll('li').forEach(item => {
      item.addEventListener('click', event => {
        alert(item.outerHTML);
        document.querySelectorAll('li').forEach(item => {
            if(item.className === "active"){
        item.classList.remove("active");
        }
        });
        item.classList.add("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!