How to get all parents until a certain parent is reached

brentonstrine picture brentonstrine · Oct 18, 2012 · Viewed 10k times · Source

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?

Answer

StaticVariable picture StaticVariable · Oct 18, 2012

You can use jquery parentsUntil() function

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