我有一块像以下的项目:
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned">
</div>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned">
</div>
所以,我有一个类owl-item
的父级,我想检查这个元素是否为空(没有任何其他子元素),如果是,则删除此元素。如果不是,请跳过。
因此,在执行我的小脚本之后,我想要:
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
答案 0 :(得分:1)
使用:empty
选择器,然后在其上调用remove()
:
$('.owl-item.cloned:empty').remove();
.owl-item {
border: 1px solid #C00;
min-height: 1em;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned"></div>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned"></div>
请注意,要使其工作,您不能在元素中包含任何空白文本节点。
如果你确实有一些空白,那么你可以使用filter()
代替:
$('.owl-item.cloned').filter(function() {
return $(this).children().length === 0;
}).remove();
.owl-item {
border: 1px solid #C00;
min-height: 1em;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned">
</div>
<div class="owl-item cloned">
<div class="item"> some other tags, text, content in item </div>
</div>
<div class="owl-item cloned">
</div>
那就是说,一个更好的解决方案是不首先克隆空元素,假设这是cloned
类的原因。