Konrad Viltersten Konrad Viltersten - 6 months ago 11
jQuery Question

What is equivalent to parent() when looking for any ancestor

When I'm looking for children of an element I use the following lines.

var myself = $(donkey);
var myProblems = myself.children("*");
var notMyProblems = myself.find("*");


However, when going in the opposite direction, I can use the line below but I haven't found the recurrent equivalent to the find method. Isn't there such thing?

var myself = $(donkey);
var problemCreator = myself.parent();


As an example, I'd like to find the table element that contains a row that contains a divisor that contains a span that contains a button that was clicked. I can do something like this.

var clickaroo = $(event.target);
var holder = clickaroo.parent().parent().parent().parent().parent();


However, it looks ugly and is fragile, in case the button is nested in an unexpected or unforseen extra div or span. I'd like to use something like this.

var clickaroo = $(event.target);
var holder = clickaroo.superParent("table");


I've googlearched for it but got nada. Am I using wrong keywords or is there no such function?

Answer

The method you're looking for is closest().

If you're trying to target elements of class findMe, you can use the following five methods.

var self = $("#myMyselfAndI");
var oneLevelDown = self.children(".findMe");
var anyLevelDown = self.find(".findMe");
var oneLevelUp = self.parent();
var anyLevelUp = self.closest(".findMe");
var allUppwards = self.parents();
Comments