Similar to jQuery .closest() but traversing descendants?

后端 未结 16 736
情书的邮戳
情书的邮戳 2020-12-07 15:13

Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is

16条回答
  •  情歌与酒
    2020-12-07 15:46

    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 $();
        },
    
    });  
    

提交回复
热议问题