How to get all parents until a certain parent is reached
Asked Answered
D

1

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?

Dys answered 18/10, 2012 at 17:52 Comment(4)
Are you looking for api.jquery.com/parentsUntil?Inspiration
scuffs shoe in dirt ...yes...Dys
When you use JavaScript for messing with CSS directly, it is usually considered to be a code smell (unless you are doing animations).Feint
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.Dys
A
27

You can use jquery parentsUntil() function

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
Acth answered 18/10, 2012 at 17:54 Comment(3)
@brentonstrine: That awkward moment when your "I'm an idiot" comment gets more upvotes than the answer itself.Branle
@MadaraUchiha: Yes, but if those upvoters are like me, then they have probably had that exact same "I'm an idiot" feeling ;-)Vena
The upvote for the answer is obvious. The upvote for the comment is to show support to the OP :)Somerset

© 2022 - 2024 — McMap. All rights reserved.