CSS and JavaScript: adding styles to active links

Maybe the quickest way to add CSS to active or current page links, it cycles through all <a> tags on the page and compares the href property to the current URL.

let a = document.querySelectorAll('a');
a.forEach((el) => {
   if (el.href == window.location.href) {
      el.style.color = "#42c500";
   }
});

In the above example the anchor’s color attribute is changed to green.

If you want to add a class to the button adjust the code to below:

let a = document.querySelectorAll('a');
a.forEach((el) => {
   if (el.href == window.location.href) {
      el.classList.add('active');
   }
});

This will add the class active to the anchor, the CSS would look like this:

a.active {
   color: 'green';
}

If you wanted to exclude some anchors from this style the below shows the CSS

a.active:not(.excluded) {
   color: 'green';
}

This will exclude any links with the class excluded from the style.

The HTML:

<a href="currentpage">Link</a>
<a href="currentpage" class="excluded">Excluded link</a>

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment Rules

  • No rude or lascivious behavior will be tolerated.
  • Beans contain the souls of the dead – do not eat them.
  • All the other obvious ones.