[jQuery] Nearest enclosing element
I've got several situations where I need to find the nearest enclosing
element of a given type. For example, I need to find the TABLE
enclosing a TD element, but there may be nested tables. Or I need to
find the TD element that was clicked on, where the event target may be
that TD or any child of the TD.
I've come up with 2 possible solutions. I'm not sure which to prefer,
or if there's a better solution.
jQuery.fn.nearestAncestor = function(filter)
{
if ( this.is(filter) ) { return this; }
return this.parents(filter).filter(':first');
};
jQuery.fn.nearestAncestor = function(filter)
{
var element = this;
do {
if ( element.is(filter) ) { return element; }
} while ( element = element.parent() );
return null;
};
Thoughts? Is this something that's common enough that it should be
added to the jQuery core?