curly_brackets
curly_brackets

Reputation: 5598

jQuery: Active state: AddClass to a link that contains the document.href as href

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??

Upvotes: 2

Views: 1739

Answers (3)

Julien
Julien

Reputation: 850

$("a[href=" + document.location.href + "]").addClass("active");

(not tested)

Upvotes: 1

SickHippie
SickHippie

Reputation: 1402

Have you tried window.location.href instead of document.location.href?

Upvotes: 0

Ry-
Ry-

Reputation: 225074

$("a").filter(function() {
    return this.href === document.location.href;
}).addClass("active");

Should work.

Upvotes: 6

Related Questions