如果给定的 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 规范,如果给定元素没有非空子节点,这将返回 true
。 Long-awaited JSFiddle demo available .
关于javascript - 如何检查元素是否匹配 :empty pseudo-class in pure JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21771512/