Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?
I know that there is
Even though it's an old topic I could not resist implementing my closestChild. Delivers the first found descendant with least traveling ( breath first ). One is recursive (personal favorite ), other using a todo list so without recursion as jQquery extensions.
Hope someone benefits.
Note : The recursive gets stack overflow, and I improved the other, now simular to previous answer given.
jQuery.fn.extend( {
closestChild_err : function( selector ) { // recursive, stack overflow when not found
var found = this.children( selector ).first();
if ( found.length == 0 ) {
found = this.children().closestChild( selector ).first(); // check all children
}
return found;
},
closestChild : function( selector ) {
var todo = this.children(); // start whith children, excluding this
while ( todo.length > 0 ) {
var found = todo.filter( selector );
if ( found.length > 0 ) { // found closest: happy
return found.first();
} else {
todo = todo.children();
}
}
return $();
},
});