Skip to content Skip to sidebar Skip to footer

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(fun

Solution 1:

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.

Solution 2:

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";
    }
}

Post a Comment for "Add Class To Href If It Links To Current Page"