jquery检查空元素并删除

时间:2015-09-08 01:42:42

标签: javascript jquery

<p>1</p>
<p>2</p>
<p></p>
<p>1</p>
<p></p>

如何删除不包含任何内容的元素?

2 个答案:

答案 0 :(得分:3)

使用.filter().remove()功能如下:

$('p').filter(function(){
   return ( $(this).text() == "" )
}).remove();

或使用.each()

$('p').each(function (i, e) {
 if ($(e).text() === "") $(e).remove();
});

使用:empty选择器更好:

$('p:empty').remove();

DEMO - 检查元素(chrome)以查看最终输出

答案 1 :(得分:1)

尝试这样做:

$('p')
    .filter(function() {
        return $.trim($(this).text()) === '' && $(this).children().length == 0
    })
    .remove()