jQuery: find() children until a certain threshold element is encountered

前端 未结 4 1298
不思量自难忘°
不思量自难忘° 2021-02-19 17:59

I have a nested table structure like

   
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 18:34

    I had a similar issue in this other question. I ended up finally figuring out a plugin on my own after going back and forth with some people trying to think of a find selector.

    USAGE : ExclusiveInputs = $('#first').findExclude('input','table');

    // Find-like method which masks any descendant
    // branches matching the Mask argument.
    $.fn.findExclude = function( Selector, Mask, result){
    
        // Default result to an empty jQuery object if not provided
        var result = typeof result !== 'undefined' ?
                    result :
                    new jQuery();
    
        // Iterate through all children, except those match Mask
        this.children().each(function(){
    
            var thisObject = jQuery( this );
            if( thisObject.is( Selector ) ) 
                result.push( this );
    
            // Recursively seek children without Mask
            if( !thisObject.is( Mask ) )
                thisObject.findExclude( Selector, Mask, result );
        });
    
        return result;
    }
    

    (Condensed Version):

    $.fn.findExclude = function( selector, mask, result )
    {
        var result = typeof result !== 'undefined' ? result : new jQuery();
        this.children().each( function(){
            var thisObject = jQuery( this );
            if( thisObject.is( selector ) ) 
                result.push( this );
            if( !thisObject.is( mask ) )
                thisObject.findExclude( selector, mask, result );
        });
        return result;
    }
    

提交回复
热议问题