Change link color of the current page with CSS

With jQuery you could use the .each function to iterate through the links with the following code:

$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});

Depending on your page structure and used links, you may have to narrow down the selection of links like:

$("nav [href]").each ...

If you are using URL parameters, it may be necessary to strip these:

if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...

This way you don’t have to edit each page.

Leave a Comment