代码片段 → jQuery 代码片段 → 检查空元素 检查空元素 Chris Coyier 于 2012 年 10 月 16 日 对找到的每个空元素执行操作 $('*').each(function() { if ($(this).text() == "") { //Do Something } }); 元素是否为空的 TRUE 或 FALSE var emptyTest = $('#myDiv').is(':empty');
这可能更实用一些
$(‘p,em,b,strong,span’).each(function() {
if (jQuery.trim ($(this).text()) == “”) $(this).css(‘border’,’solid 1px red’);
});
谢谢 Cipa!
嘿,Chris,我认为你错过了 :empty 周围的单引号
.is(‘:empty’)
不完全是,怎么样 ”
“?它不为空,但没有文本。我认为检查 childNodes 属性更好。
$(‘*’).each(function() {
if (!this.childNodes.length) {
// 执行操作
}
});
我之前回复中的双引号内容被过滤了,这里给出
<div><img/></div>
谢谢 Cipa!我认为 trim 有所不同。
不错……