簡體   English   中英

如何刪除相互嵌套的 html 元素?

[英]How can I remove html elements that are nested into each other?

我有一個這樣的 html 結構:

<p>Hello</p>
<h1>ah</h1>
<child>
    <p>Haha</p>
    <child>
      <p>Hihi</P>
    </child>
</child>
<child>
<h4>Hello</h4>
</child>
<h3>Hello</h3>

目標:

我的目標是從 DOM 中刪除所有子標簽來接收這個:

<p>Hello</p>
<h1>ah</h1>
<h3>Hello</h3>

我試過的:

const html = document.createElement('div');
//This is the HTML I pasted above.
html.innerHTML = this.item.Body;
let childTags = html.getElementsByTagName('child');

for (let i = 0; i < childTags.length; i++) {
  let childTag = childTags[i];
  childTag.remove();
}

this.item.Body = html.innerHTML;

我的問題:

我遇到的問題是getElementsByTagName找到在我刪除父子標記時已經刪除的嵌套標記,這使得 for 循環不起作用。

任何幫助表示贊賞。

我自己解決了,而且非常簡單。

我不得不做一個遞歸函數。

 removeChildComponents() { const html = document.createElement('div'); html.innerHTML = this.item.Body; let childTag = html.getElementsByTagName('child'); if (childTag.length > 0) { childTag[0].remove(); } this.item.Body = html.innerHTML; const recursionHandler = html.getElementsByTagName('child') if (recursionHandler.length > 0) { this.removeChildComponents(); }; };

干得好。 首先,您getElementsByTagName返回一個HTMLCollection ,您可以使用Array.prototype.slice將其轉換為數組。 然后對於forEach子項,即數組中的項,您從 DOM 中.remove()它。

 Array.prototype.slice.call(document.getElementsByTagName('child')).forEach(child => child.remove());
 <p>Hello</p> <h1>ah</h1> <child> <p>Haha</p> <child> <p>Hihi</p> </child> </child> <child> <h4>Hello</h4> </child> <h3>Hello</h3>

暫無
暫無

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

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