Harugawa Harugawa - 5 months ago 8
Javascript Question

When on homepage, whole my navigation is highlighting

I'm using this code

$(document).ready(function () {
$(function () {
$('li a[href^="../../' + location.pathname.split("/")[1] + '"]').addClass('active');

to highlight my navigation, depending on which page I'am.

It works fine and highlights only one link from navigation if I'm on for example
, but when I get on home page aka
It highlights all of the li from navigations at once..

Tried to reproduce it in jsfiddle... but couldnt cause it would then redirect you to some other page or tell that page does not exists

Is there anything I can do?


How about using the "ends with" operator $= instead of "starts with" ^=

In this way you could just check for everything after the domain name. Just exclude the pathname that only contains the domain by using an "if":

$(document).ready(function () {
        if(location.pathname != "/") {
            $('li a[href$="' + location.pathname+ '"]').addClass('active');

Also have a look at these two post:

Select <a> which href ends with some string