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

123
Views
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 answers
Answer question

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 Report

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 Report

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