删除没有文本的段落

Remove paragraphs with no text

本文关键字:段落 文本 删除      更新时间:2023-09-26

有没有一种方法可以删除没有文本的段落,但其中可能有空的html标记?

例如

<p><strong><br></strong></p> or <p></p> or <p>&nbsp;</p>

将被删除,但

<p><strong>hi<br>there</strong></p> or <p>hi there</p>

不会被删除

使用jQuery循环遍历所有p个元素,然后只获取其中的文本,对其进行修剪(因此只保留空格也会被删除),然后检查其中是否有文本,如果没有,则将其删除。

$('p').each(function() {
    if ($(this).text().trim() == "") {
        $(this).remove();
    }
});

jsfiddle示例:http://jsfiddle.net/ygbnpg77/

如果你想用javascript在前端实现这一点,你可以这样做。

$(document).ready(function(){
    $('p').each(function(){
           if($(this).html().length == 0)
           {
               $(this).remove();
           }
    })
})