16

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?

brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • Are you looking for http://api.jquery.com/parentsUntil/? – wirey00 Oct 18 '12 at 17:53
  • *scuffs shoe in dirt* ...yes... – brentonstrine Oct 18 '12 at 17:57
  • When you use JavaScript for messing with CSS directly, it is usually considered to be a *code smell* (unless you are doing animations). – tereško Oct 18 '12 at 18:12
  • 1
    It's unavoidable because I'm working on top of plugins that are already doing this to excess. I had a perfect CSS-only solution that is ruined by tons of competing `style=""` changes being made by these stupid plugins. – brentonstrine Oct 18 '12 at 18:14

1 Answers1

27

You can use jquery parentsUntil() function

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
StaticVariable
  • 5,253
  • 4
  • 23
  • 45