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

275
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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