【问题标题】:Scan the DOM upward to find element matching selector (no jQuery)向上扫描 DOM 以查找元素匹配选择器(无 jQuery)
【发布时间】:2018-11-14 01:04:42
【问题描述】:

我想要一个函数,它可以从 DOMElement 向上扫描 DOM,并在向上扫描每个父级的子级。

它必须继续运行,直到找到与参数中接收到的选择器匹配的任何<element>。选择器必须是任何类型的有效 CSS 选择器。

也需要用纯 JS(没有 jQuery)来完成

【问题讨论】:

  • 这确实不是help center 中概述的正确问题。这实际上只是一个没有特定代码相关问题陈述的目标
  • @Bram Vanroy:querySelector/All 无法匹配元素的祖先。
  • 我现在意识到 OP 只关注祖先的孩子,而不是他们的所有后代。 (这是有道理的——否则你可以在 ROOT 上做一个 querySelector。)

标签: javascript html dom css-selectors


【解决方案1】:

我最终制作了这个函数的修改版本 I found on this site。您可以随心所欲地使用此功能,扩大规模,认领它,随心所欲。

这是我找到的解决方案

GetClosest = function (elem, selector) {

    for (; elem && elem !== document.body; elem = elem.parentNode) {

        // If the elem matches at first iteration.
        if(elem.matches(selector)) {

            return elem;

        } else {

            // Scans all the childs of current iterated element (always higher in DOM until found).
            // If one matches the selector it'll stop and return it.
            child = elem.parentNode.firstChild;
            do {

                if(child.nodeType === 3) continue; // text node
                if(child.matches(selector)) return child;

            } while (child = child.nextElementSibling);
        }
    }

    return null;

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多