user3892090
user3892090

Reputation: 61

How to add class inside li?

I have an unordered list and I am using the following code to add class to the current link I visited.

$("li a").filter(function(){
    return this.href == location.href.replace(/#.*/, ""); }).addClass("selected");

The outcome is: <li><a href="#" class="selected">Link1</a></li>

But the solution I need is: <li class="selected"><a href="#">Link1</a></li>

Please help. Thank you.

Update: Most of the current answers works fine. However, I encountered another problem.

The parent li has submenus. Upon clicking a submenu link, the "selected" class of the parent li is gone. Is there a way to make the "selected" class stays on parent li as well? Or if it's possible to just add the class just on the parent li, and not on any clicked submenu link? Thank you in advance for your help again. :)

Upvotes: 2

Views: 303

Answers (4)

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

i think this should do it

$("li a").filter(function(){
return this.href == location.href.replace(/#.*/, ""); }).parent('li').addClass("selected");

edit

$("li a").filter(function(){ return this.href == location.href.replace(/#.*/, ""); }).parents('li, li:first').addClass("selected");

Upvotes: 1

Mad Angle
Mad Angle

Reputation: 2330

 $("li a").filter(function(){
        return this.href == location.href.replace(/#.*/, ""); }).closest('li').addClass("selected");

Upvotes: 1

Barlas Apaydin
Barlas Apaydin

Reputation: 7315

Cleaner and optimized way:

var targetUrl = window.location.href.replace(/#.*/, "");
var activeNav = $('li a[href="'+ targetUrl +'"]');
if ( activeNav.length ) {
    activeNav.parent('li').addClass('selected');
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are filtering the anchor element, not the li so the addClass() will add the class to the a element. You can use a ancestor lookup(.parent(), .closest()) to find the desired li element and then use addClass()

$("li a").filter(function () {
    return this.href == location.href.replace(/#.*/, "");
}).parent().addClass("selected");

Upvotes: 2

Related Questions