Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all parents until a certain parent is reached

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?

like image 593
brentonstrine Avatar asked Oct 18 '12 17:10

brentonstrine


People also ask

How to get all parents in JavaScript?

Get all parents # var getParents = function (elem) { // Set up a parent array var parents = []; // Push each parent element to the array for ( ; elem && elem !== document; elem = elem. parentNode ) { parents. push(elem); } // Return our parent array return parents; };

What is parentsUntil?

parentsUntil() method traverses through the ancestors of these elements until it reaches an element matched by the selector passed in the method's argument. The resulting jQuery object contains all of the ancestors up to but not including the one matched by the . parentsUntil() selector.

What is find in jQuery?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.


1 Answers

You can use jquery parentsUntil() function

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
like image 147
StaticVariable Avatar answered Oct 12 '22 09:10

StaticVariable