如果给定的HTML元素为空,如何在纯JavaScript (没有jQuery,没有库)中检查?我对“空”的定义与CSS :empty pseudo-class相同。因此,如果给定元素与:empty
选择器匹配,那么我想知道它。
答案 0 :(得分:5)
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
答案 1 :(得分:4)
确保spec合规性的一种方法是使用.querySelectorAll
或.matches
。
function matches(el, selector) {
return !!~[].indexOf.call(el.ownerDocument.querySelectorAll(selector));
}
取决于browser support的需求,.matches
is more direct甚至适用于分离的节点:
function matches(el, selector) {
return !!(el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector).call(el, selector);
}
使用以下任何一种:
matches(el, ':empty')
答案 2 :(得分:1)
据我所知,jQuery's implementation of :empty
完全匹配规范,因此可以用作参考。从撰写本文时的latest version开始:
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
}
答案 3 :(得分:-1)
我认为最简单,最简单的方法是:
elem = document.getElemntById('id_of_the_elem');
function isEmpty(elem){
if(elem.innerHTML=='') console.log("empty tag");
else console.log('Non empty tag');
}