jQuery: Active state: AddClass to a link that contains the document.href as href
-
14-11-2019 - |
Question
I'm wondering if its possible to addClass to a link, that has the same href as the document.href?
I tried, but without any luck.
if ($("a").attr("href") == document.location.href) {
$(this).addClass("active");
}
Isn't this possible??
Solution
$("a").filter(function() {
return this.href === document.location.href;
}).addClass("active");
Should work.
OTHER TIPS
$("a[href=" + document.location.href + "]").addClass("active");
(not tested)
Have you tried window.location.href instead of document.location.href?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow