javascript - 如何检查元素是否匹配 :empty pseudo-class in pure JS?

标签 javascript html css css-selectors

如果给定的 HTML 元素为空,我如何在纯 JavaScript(没有 jQuery,没有库)中检查?我对“空”的定义与 CSS :empty pseudo-class 相同.因此,如果给定元素与 :empty 选择器匹配,那么我想知道它。

最佳答案

function isEmpty (el) {
    if (!el.hasChildNodes()) return true;

    for (var node = el.firstChild; node = node.nextSibling;) {
        var type = node.nodeType;
        if (type === 1 && !isEmpty(node) || // another element
            type === 3 && node.nodeValue) { // text node
            return false;
        }
    }
    return true;
}

根据 CSS 规范,如果给定元素没有非空子节点,这将返回 trueLong-awaited JSFiddle demo available .

关于javascript - 如何检查元素是否匹配 :empty pseudo-class in pure JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21771512/

相关文章:

html - 使用 html 部分标记时在 CSS-Grid 中提供相同的 css 属性

css - 同步使用自动前缀

html - Box Div 顺序错误

javascript - 在数据表中隐藏动态创建的 DIV

javascript - 如何使动态表格堆叠在彼此之下?而不仅仅是创建更多的数据单元

javascript - 如何永久更改对象的样式?

javascript - For 循环 使用 & 连接

html - 无法在仅 CSS 菜单中添加第二个子级菜单

html - 如何对齐容器内文本旁边的图像?

html - .class :nth-child(even) not working?