2009-11-12 52 views
1

我試圖找出一個可能包含註釋標記和/或空白區域的空元素。如何使用jQuery來識別可能包含註釋標記的空元素?

以下HTML結構在環境中常見的地方我的工作:

<div class="container container-no-title"> 
    <div id="dnn_ctr6735_ContentPane" class="container-padding DNNAlignright"> 
    <!-- Start_Module_6735 --> 
    <div id="dnn_ctr6735_ModuleContent"> 
     <!-- End_Module_6735 --> 
    </div> 
    </div> 
</div> 

我最初的jQuery是:

$('.container-padding > div').each(function() { 
    if ($(this).is(":empty")) { 
    $(this).parent('.container-padding').remove(); 
    }; 
}); 

但這並不佔空格或註釋標記。我發現了其他一些解決空白問題的問題,但沒有涉及評論標籤的問題,我真的很想保留這個簡單的jQuery片段。

乾杯, 史蒂夫

回答

4

你試過:

$('.container-padding > div').each(function() { 
    if ($(this).text().match(/^\s*$/)) { 
     $(this).parent('.container-padding').remove(); 
    } 
}); 

甚至

$('.container-padding').each(function() { 
    if ($(this).text().match(/^\s*$/)) { 
     $(this).remove(); 
    } 
}); 
+0

我有,這解決了空白,但沒有解決評論標籤。 – 2009-11-12 21:18:53

+0

那麼爲什麼不添加評論標籤的正則表達式測試,並完成它呢? – 2009-11-12 21:20:03

+0

你的意思是說,如果有評論標籤,你不想刪除元素?在我的測試中,您可以成功匹配並移除內部容器。 – tvanfosson 2009-11-12 21:20:35

0

註釋不是DOM樹的一部分,所以據我所知沒有辦法,你可以訪問它們。

+0

這是一個很好的答案,值得一些掌聲,但我不敢相信有沒有解決方案! – 2009-11-12 21:20:38

1

如果我理解正確的空元素不應該有孩子:

$(this).children().length == 0

Would'nt做的jQuery爲你忽略空白和評論的工作?

+0

我認爲這個想法是,如果它只包含一個空的孩子,評論或空白,它應該被刪除。 – tvanfosson 2009-11-12 21:35:52

1

很高興電視的解決方案爲你工作。您還可以直接使用DOM來查找不是「元素」的節點,方法是檢查nodeType值。

例如,遍歷element.childNodes:

if (element.childNodes[i].nodeType != 1) 
// node is not an element (text/whitespace or comment) 

或:

if (element.childNodes[i].nodeType == 8) 
// node is a comment 

檢查here獲取更多信息。

相關問題