2013-10-25 100 views
0

我想從某些html字符串中刪除空元素。我知道我可以運行類似於:從html中遞歸刪除空節點

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

問題是我想要刪除所有空節點 - 不僅是p。我還希望腳本將<p><span></span></p>中的p節點視爲空,因爲它僅包含空元素。你有這樣的簡單實現嗎?我忘了添加:我可以使用jQuery,但我想要遍歷和編輯的html是一個字符串 - 而不是實際的文檔。那麼我怎麼做這個操作呢?我試着用var html = $.parseHTML('<p><span></span></p>')但每個循環後,我仍然得到同樣的串...

+0

要選擇所有元素,$( '*'),但要小心那麼,刪除一個元素列表可能更爲安全,例如刪除元素$('p,h1,h2')或類似的東西,因爲您可能不想刪除


標記。至於嵌套元素,我不確定。 – ivarni

+0

Refere this http://jsfiddle.net/LEKaL/6/ – Roopendra

+0

應該只包含製表符,換行符和其他空標記的元素是否也被檢測爲空? (例如'

\ n \ n

') –

回答

3

最近我一直在尋找A S解決同樣的問題。遞歸函數就是答案。

function removeEmptyTagsRecursively($el) { 
    if ($el.children().length) { 

     $el.children().each(function(i, val) { 
      removeEmptyTagsRecursively($(val)); 
     }); 

     $el.children(':empty').remove(); 
    } 
} 

小提琴這裏:https://jsfiddle.net/635utakr/9/

+0

優秀的遞歸函數示例:) –

0

嘗試像

do { 
    empty = $("*:empty"); 
    count = empty.length; 
    empty.remove(); 
} 
while (count > 0); 

它的迭代而不是遞歸的,但應該做的伎倆

0

其實你的代碼工作很好。看到這個fiddle

它只顯示,裏面有內容。然後你想要什麼?

HTML

<p>hi 1</p> 
<p></p> 
<p><span>hi 2</span></p> 
<p><span></span></p> 

腳本

$('p').each(function(index, item) { 
    if($.trim($(item).text()) === "") { 
     $(item).remove(); 
    } 
}); 
+0

請參閱我的編輯... Actualy我不想對html文檔進行操作,但需要一些自定義字符串 - 這意味着$(item).remove()並不完全適用。 – Moby04

+0

更好,再給一些代碼 – KarSho

0

您可以通過下面的代碼實現這一點: -

function removeEmptyTag(root) { 
    var $root = $(root); 
    $root.contents().each(function() { 
    if (this.nodeType === 1) { 
     removeEmptyTag(this); 
    } 
    }); 

    if (!$root.is("area,base,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr") && !$root.html().trim().length) { 
    $root.remove(); 
    } 
} 

removeEmptyTag("#divIdHere"); 

Fiddle

0

這裏是Paul's function香草JS一個tweek(需要Element.matches() polyfill):

function removeEmpty(parent) { 
    // for each child 
    [].forEach.call(parent.children, function(child) { 
     // repeat operation 
     removeEmpty(child); 

     // remove if it matches selector 
     if (child.matches(':empty')) { 
      parent.removeChild(child); 
     } 
    }); 
}