簡體   English   中英

使用JavaScript刪除HTML h1空標記

[英]Remove HTML h1 empty tag using javascript

如何僅使用JavaScript刪除h1空標簽?

<h1>Hello Plunker!</h1>
<p>adadasdasdasdsaddasd</p>


<h1></h1>
<p>adadasdasdasdsaddasd</p>

<h1></h1>
<p>adadasdasdasdsaddasd</p>

<h1></h1>
<p>adadasdasdasdsaddasd</p>

您可以

var els = document.querySelectorAll('h1'), //find all h1
    el;
for (var i = 0; i < els.length; i++) {
    el = els[i];
    //if there is no first child 
    if (!el.firstChild) {
        //remove the node
        el.parentNode.removeChild(el)
    }
}

演示: 小提琴

如果您使用jQuery,請嘗試以下操作:

  $('h1').each(function(){
       if($(this).is(':empty')){
         $(this).remove()
       }
    });

有關更多信息,請參見http://api.jquery.com/is/http://api.jquery.com/empty-selector/

也可以嘗試使用CSS空標簽:

http://codepen.io/anon/pen/aOOmOj

h1:empty { background: #ccc; display:none; }

使用javascript的最簡單解決方案:

while (!document.getElementsByTagName('h1')[0].remove()) {}

是的,我知道,只要不再有h1 ,循環就會以

TypeError: ... is undefined`.

但是,這 簡單

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM