Similar to jQuery .closest() but traversing descendants?

后端 未结 16 711
情书的邮戳
情书的邮戳 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:56

    In case someone's looking for a pure JS solution (using ES6 instead of jQuery), here's the one I use:

    Element.prototype.QuerySelector_BreadthFirst = function(selector) {
        let currentLayerElements = [...this.childNodes];
        while (currentLayerElements.length) {
            let firstMatchInLayer = currentLayerElements.find(a=>a.matches && a.matches(selector));
            if (firstMatchInLayer) return firstMatchInLayer;
            currentLayerElements = currentLayerElements.reduce((acc, item)=>acc.concat([...item.childNodes]), []);
        }
        return null;
    };
    
    0 讨论(0)
  • 2020-12-07 15:56

    You can just simply put,

    $("#find-my-closest-descendant").siblings('.closest:first');
    
    0 讨论(0)
  • 2020-12-07 15:57

    You can use find with the :first selector:

    $('#parent').find('p:first');
    

    The above line will find the first <p> element in the descendants of #parent.

    0 讨论(0)
  • 2020-12-07 15:57

    you have a lot of options, however $("#parent").children(".child"); is the fastet. check this article for details and benchmark

    0 讨论(0)
  • 2020-12-07 15:58

    If by "closest" descendant you mean the first child then you can do:

    $('#foo').find(':first');
    

    Or:

    $('#foo').children().first();
    

    Or, to look for the first occurrence of a specific element, you could do:

    $('#foo').find('.whatever').first();
    

    Or:

    $('#foo').find('.whatever:first');
    

    Really though, we need a solid definition of what "closest descendant" means.

    E.g.

    <div id="foo">
        <p>
            <span></span>
        </p>
        <span></span>
    </div>
    

    Which <span> would $('#foo').closestDescendent('span') return?

    0 讨论(0)
  • 2020-12-07 15:59

    I would use the following to include the target itself if it matches the selector:

        var jTarget = $("#doo");
        var sel = '.pou';
        var jDom = jTarget.find(sel).addBack(sel).first();
    

    Markup:

    <div id="doo" class="pou">
        poo
        <div class="foo">foo</div>
        <div class="pou">pooo</div>
    </div>
    
    0 讨论(0)
提交回复
热议问题