Konrad Viltersten
Konrad Viltersten

Reputation: 39250

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?

Upvotes: 0

Views: 134

Answers (2)

Rune FS
Rune FS

Reputation: 21752

If you want to search upwards in the DOM there are a few options. If you use .parent() it will look for an immediate parent of the node but if you use parents(selector) the search will traverse the tree upwards, returning all matches. So instead of find you can do this

var myself = $(donkey);
var parents = myself.parents();

Upvotes: 1

user1675891
user1675891

Reputation:

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();

Upvotes: 2

Related Questions