Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
Adding an active class to the navbar

This is how my code looks like:

<div class="header-nav navbar-collapse collapse ">
      <ul id="navigation" class=" nav navbar-nav">       
                   <li>
                        <a href="index.html">Home</a>
                                
                   </li>
                            
                    <li>
                        <a href="about-us.html">About Us</a>
                    </li>
                     
                    </ul>
                    </div>

I've been trying to add the active class to each of them when the user is on that specific page but no succes so far Tis is how my script looks like:

     var i = 0;
  [].forEach.call(document.querySelectorAll('li > a'), function(nav) {
    console.log(nav.pathname,window.location.pathname);
    if (nav.pathname === window.location.pathname){
        i = 1;
        console.log(i);
      nav.classList.add('active')
    }
        
    else{
         console.log(i)
         nav.classList.removeClass('active')
  }
    

  })           

The active class is set on the "a" not on "li" and i don't know how to fix this. Maybe someone can help me?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

To target the parent element, you have a few options - my favorite is element.closest(selector) which takes a starting element and finds the closest containing parent that matches selector

let els = document.querySelectorAll('li > a');
els.forEach(el => {
  el.addEventListener('click', e => {
    els.forEach(a => a.closest('li').classList.remove('active'));
    e.target.closest('li').classList.add('active');
  })
})
li.active {
  background-color: green;
}
<ul>
  <li><a href='#'>link 1</a></li>
  <li><a href='#'>link 1</a></li>
  <li><a href='#'>link 1</a></li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório

0

In looking at the classes, it looks like you may be using Bootstrap. I added in those libs to the snippet, and updated some of the classes. I also added in another nav item with the href equal to js since that is the pathname for the snippet window. Otherwise it won't add the active class as there would not be a pathname that would be equal.

I also changed the nav items to pills, so you can see the active link easier.

var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
    console.log({
      navPathname: nav.pathname,
      windowLocationPathname: window.location.pathname,
      areEqual: nav.pathname === window.location.pathname,
    });
  if (nav.pathname === window.location.pathname) {
    nav.classList.add('active')
  } else {
    nav.classList.remove('active')
  }
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<div class="navbar navbar-light bg-light">
  <ul id="navigation" class="nav nav-pills">
    <li class="nav-item">
      <a class="nav-link" href="index.html">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="js">JS</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="about-us.html">About Us</a>
    </li>
  </ul>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks for this, i merged the two responses and made it into one that works for me, this is the script that worked without even touching the classes into the nav-bar:

    document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
    console.log({
      navPathname: nav.pathname,
      windowLocationPathname: window.location.pathname,
      areEqual: nav.pathname === window.location.pathname,
    });
  if (nav.pathname === window.location.pathname) {
    nav.closest('li').classList.add('active')
  } else {
    nav.closest('li').classList.remove('active')
  }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda