Reputation: 143
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
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
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