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?
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; };
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.
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.
You can use jquery parentsUntil()
function
$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With