将 class 应用到 child 中的 parents,除了所选的 - JQuery

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

我正在尝试将 class 应用到 child 的每个 parent 元素,除了我选择的 child。

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

这会将 class 应用到我选择的一个,我希望它应用到这一个的每个 parent APART。我相信我可以使用 :not 选择器,但它似乎不想工作。

谢谢。

你可以获取所有.myParentName然后排除当前父

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

另一种方式可能是

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