2013-03-07 82 views
0

我在一個泡菜。我試圖實現的是刪除一個div,如果它是空的,然後做我以後要做的事情,這很容易。困難的部分是試圖刪除空標籤。我使用的是DNN,它喜歡把p和br這樣的空標籤。我希望能夠在執行檢查之前將其刪除。這是到目前爲止我的代碼如何使用javascript刪除標籤?

$(document).ready(function(){ 
var element = document.getElementsByTagName("p"); //Need to remove all tags. not just P 
element.parentNode.removeChild(element); //Doesn't target which child 

if(!$.trim($('#container2Test').html()).length) { 
    alert("empty"); 
    $('#container2Test').remove(); 
    $('#container3Test').css({'width' : '50%', 'background-color' : '#3F0'}); 
    $('#container3Test').append("This is some content"); 
} 
else{ 
    alert("not empty"); 
} 
}); 

的HTML:

<div id="container1Test" style="width:30%; height:10em; background-color:#000;"> 
</div> 
<div id="container2Test" style="width:50%; height:10em; background-color:#666;"> 
    <p></p><br /><p></p> 
</div> 
<div id="container3Test" style="width:20%; height:10em; background-color:#F66;"> 
</div> 
</html 

我試過很多選項,試圖移除標籤,但我已經沒有這樣的運氣:(請幫助

+1

'element'是一個數組。 (實際上是一個NodeList) – SLaks 2013-03-07 03:40:51

回答

2

至於你container2test塊進入,請嘗試使用.text()代替.html(),這會忽略得到插入空標籤和只專注於文本內容。

關於它上面的一塊,我不太清楚你想達到什麼目的。如果您執行前面提到的更改,我認爲不需要。

+0

哈哈......你說得對。將其更改爲.text()確實會忽略空標籤,並且所有內容都按預期進行。甚至不需要上面的代碼。非常感謝您的迴應!不勝感激! – 2013-03-07 03:45:22

-1

注意getElementsByTagName是複數:

var elements = document.getElementsByTagName("p"); 
for (var n=0; n < elements.length; n++) { 
    var element = elements[n]; 
    element.parentNode.removeChild(element); // should work now 
} 
+0

我嘗試過使用它,但沒有達到我實現的目標。非常感謝! – 2013-03-07 05:59:14

1

我認爲這將是你所需要的解決方案...退房是:

var elmsToClear = $('#container1Test, #container2Test, #container3Test'); 
elmsToClear.each(function(){ 
    while($(this).find('*:empty').remove().length); // recursivly kill all empty elements 
    if(!$(this).find('*').length){ // if no elements left - kill the parent 
     alert($(this).attr('id') + ' is empty...'); 
     $(this).remove(); 
    } 
    else{ // there is something in here... 
     alert($(this).attr('id') + ' is NOT empty...'); 
    } 
}); 

>>>The JS-Fiddle of the Problem with Solution < < <

問候;)

+0

偉大的解決方案,但我有我的答案,謝謝堆雖然少! – 2013-03-07 05:58:48

-1

有一個removeChild()函數。那麼,爲什麼你不能做這樣的事情:

$('div').each(function(){ 
    if(this.innerHTML == ''){ 
     this.parentNode.removechild(this); 
    } 
}); 

(沒有測試)