Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda