jord49
jord49

Reputation: 582

Apply class to parents of child apart from the one selected - JQuery

Im trying to apply a class to every parent element of a child apart from the child I have selected.

 $('.myChildName').parents('.myParentName').toggleClass("applyStyle");

This applies the class to one I have selected, I want it to apply to every parent APART from this one. I believe i can use the :not selector but it doesnt seem to want to work.

Thanks.

Upvotes: 1

Views: 39

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can get all .myParentName then exclude the current parent

$('.myParentName').not($('.myChildName').parents()).toggleClass("applyStyle");// also $('.myChildName').closest('.myParentName') instead of $('.myChildName').parents()

Another way could be

$('.myParentName:not(:has(.myChildName))').toggleClass("applyStyle");

Upvotes: 5

Related Questions