Add class to href if it links to current page

I'm currently trying to make a javascript function to check if a link on the page links to the same page, and if so, add a class to it.

What I currently have:

$(document).ready(function() {
  var currentPage = location.pathname;
  if $("a[href*=currentPage]") {
  $("a").addClass( "active" );
  }
});

However, this doesn't seem to work. Any help appreciated.

Upvotes: 1

Views: 3102

Answers (2)

Eugene_Dv
Eugene_Dv

Reputation: 101

You can use pure JavaScript (IE 9 and above)

var currentPage = location.href;
var allA = document.getElementsByTagName('A');
for(var i = 0, len = allA.length; i < len; i++) {
    if(allA[i].href == currentPage) {
         allA[i].className = "active";
    }
}

Upvotes: 2

Jonas Grumann
Jonas Grumann

Reputation: 10786

var currentPage = location.pathname;
$('a').each(function() {
    var currentHref = $(this).attr('href');
    if(currentHref == currentPage) {
        $(this).addClass("active");
    }
})

Should do the trick. Pay attention to the fact that some links might include the domain.

Upvotes: 3

Related Questions