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

281
Vistas
How to add and remove the active class on the various sections of my HTML nav bar using JavaScript?

I have a nav bar that has four different section names of the webpage. When I click on one of the section names, I want it to be active (highlighted) and I want the previous active section name to no longer be active. I have been trying many different JavaScript functions and code, but have not been able to succeed. If anyone can look at my code and let me know what I am missing or doing wrong, that would be amazing. Please let me know if you have any questions with my code or problem, I will be happy to answer. Thank you.

HTML Code (navbar.html):

<nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav">
            <a class="navbar-brand js-scroll-trigger" href="#about">
                <span class="d-block d-lg-none">Joseph Smith</span>
                <span class="d-none d-lg-block"><img class="img-fluid img-profile rounded-circle mx-auto mb-2" src="{% static 'img/joseph_headshot.jpg' %}"alt="..." /></span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
            <div class="collapse navbar-collapse" id="navbarResponsive">
                <ul class="navbar-nav">
                    <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li>
                    <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li>
                </ul>
            </div>
        </nav>

JavaScript Code (script.js):

responsiveNavItems.map(function (responsiveNavItem) {
        responsiveNavItem.addEventListener('click', () => {
            const curr_active = document.getElementsByClassName("navbar-nav").getElementsByTagName('li').getElementsByClassName(".active");
            curr_active[0].className = curr_active[0].className.replace(" active", "");
            responsiveNavItem.className += " active";
            }
        });
    });
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I think the main problem may be the period before "active" when looking for elements with that class name.

Try this...

responsiveNavItems.map(function (responsiveNavItem) {
  responsiveNavItem.addEventListener('click', nav_link_click);
});

function nav_link_click() {
  const curr_active = document.getElementsByClassName('navbar-nav').getElementsByTagName('li').getElementsByClassName('active');
  curr_active[0].classList.remove('active');
  this.classList.add('active');
}
about 4 years ago · Santiago Trujillo Denunciar

0

You can use querySelector(). It allows you to find the first element that matches one or more CSS selectors. You can call the querySelector() method on the document or any HTML element.

function myFunction(e) {
  var elements = document.querySelector(".active");
  if(elements !==null){
   elements.classList.remove("active");
  }
 e.target.className = "active";
}
about 4 years ago · Santiago Trujillo 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