Actually, jQuery has no a method that returns _first_ ancestor that matches required condition:

— jQuery.parent() returns first _direct_ parent;
— jQuery.parents() returns _all_ ancestors, not just first matching one.

An appropriate name for method you're requesting would be probably Node.ancestor().

For maximum script performance, it may make sense to have two separate methods (similar to having separate querySelector() and querySelectorAll() methods):

— ancestor() returns _first_ matching ancestor and then immediately stops searching up the DOM tree;
— ancestors() returns _all_ matching ancestors from the node to document's root element.
16.12.2011, 02:41, "Ojan Vafai" <>:
Another jquery inspired addition: we should add a "parent" method to Node that takes a CSS selector or a function. It walks up the tree until it finds a node that matches the selector/function.
node.parent() <-- returns node.parentNode
node.parent('div') <-- returns the first ancestor of node (walking up) that is a div
node.parent(function(ancestor) { return ancestor.getAttribute("foo") == "bar" }) <-- returns the first ancestor of node whose "foo" attribute has the value "bar"
Open questions:
1. Should all selectors be allowed or just simple selectors? The former is easier to understand and more powerful but also easy to shoot yourself in the foot with (e.g. combinators can easily result in n^2 walks of the ancestor chain).
2. What should happen in the following cases? My intuition is that they should all return either null or node.parentNode, but I don't feel strongly.
I also think we should add "next" and "previous" that do the same thing as "parent" except they walk the sibling list, but I'm less convinced those are as useful.