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.
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.
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";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.