如何让所有父母到达某个父母

时间:2022-03-26 08:26:18

I need something in-between the functionality of .closest() and .parents(). I am applying some CSS to all parents of a certain element up to a certain parent. Right now I'm while looping up, but it seems like there is a better way to do this.

我需要介于.closest()和.parents()的功能之间。我将一些CSS应用于某个元素的所有父母,直到某个父母。现在我正在循环,但似乎有更好的方法来做到这一点。

var goUp = $(".distant-child");
while(!goUp.hasClass("ancestor-to-stop-at")){
    goUp.css("height","100%");
    goUp = goUp.parent();
}

I'd rather do something like one of these:

我宁愿做其中一件事:

$(".distant-child").closest(".ancestor-to-stop-at").css("height","100%"); //won't work because .closest() only returns the top ancestor
$(".distant-child").parents(".ancestor-to-stop-at").css("height","100%"); //won't work because .parents() doesn't take this parameter and won't stop at the specified element.

How can I achieve this without a while loop?

如何在没有while循环的情况下实现这一目标?

1 个解决方案

#1


24  

You can use jquery parentsUntil() function

您可以使用jquery的parentsUntil()函数

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");

#1


24  

You can use jquery parentsUntil() function

您可以使用jquery的parentsUntil()函数

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");