Вопрос

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.

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?

Это было полезно?

Решение

You can use jquery parentsUntil() function

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top