MasterNone
MasterNone

Reputation: 568

Targeting parent classes and adding a class to them

Simply put I have one menu, sub-menu and sub-submenu so to speak and rhe sub-submenu has active link with a class of .current-menu-item . Now I want to traverse upward in the DOM finding it's parent .menu-item-has-children and its parent .menu-item-has-children and add a class to both of them .current-menu-sub.

$(".sidebar li.current-menu-item").parents().hasClass('menu-item-has-children') {
  $('.menu-item-has-children').addClass("current-menu-sub");
};

This is my code, but somethings quite not right.

Upvotes: 1

Views: 50

Answers (3)

Edmar Miyake
Edmar Miyake

Reputation: 12390

Just add the'.menu-item-has-children' parent selector to parents()

$(".sidebar li.current-menu-item").parents('.menu-item-has-children').addClass("current-menu-sub");

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

Close but hasClass is not a dom searching function

You just need to pass the parents selector(s) to parents()

$(".sidebar li.current-menu-item")
        .parents('.menu-item-has-children')
        .addClass("current-menu-sub");

Upvotes: 1

trincot
trincot

Reputation: 350272

You can pass a selector in .parents() and apply .addClass() to all of those that match by chaining that method to it:

$(".sidebar li.current-menu-item").parents('.menu-item-has-children')
                                  .addClass("current-menu-sub");

Upvotes: 1

Related Questions