Similar to jQuery .closest() but traversing descendants?

后端 未结 16 759
情书的邮戳
情书的邮戳 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;
    };
    

提交回复
热议问题