2015-03-02 54 views
0

有沒有一種方法可以刪除段落中沒有文字,但可能有空的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> 

不會被刪除

+1

有關使用整齊什麼? http://tidy.sourceforge.net/ – alfallouji 2015-03-02 18:21:19

回答

2

通過所有p元素使用jQuery循環,那麼得到的只是它的文本,修剪(所以只是有空間也被刪除),然後檢查是否有文本在裏面,如果有ISN」 t,刪除它。

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

的jsfiddle例如:http://jsfiddle.net/ygbnpg77/

1

那麼,如果你想這樣做前端明智的,你可以做到這一點的JavaScript。

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

}) 
+0

如果段落包含標籤,這將不起作用。給定'


',$(this).html()將等於'
'。 – 2015-03-02 19:09:38