简体   繁体   English

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

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

I have an html structure like this:我有一个这样的 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>

Goal:目标:

My Goal is to remove all child tags from the DOM to receive this:我的目标是从 DOM 中删除所有子标签来接收这个:

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

What I tried:我试过的:

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;

My Problem:我的问题:

The problem that I am having is that getElementsByTagName finds the nested tag that is already removed when I remove the parent child tag, this makes it so the for loop doesn't work.我遇到的问题是getElementsByTagName找到在我删除父子标记时已经删除的嵌套标记,这使得 for 循环不起作用。

Any help appreciated.任何帮助表示赞赏。

I solved it myself, and it was embarassingly easy.我自己解决了,而且非常简单。

I had to make a recursive function.我不得不做一个递归函数。

 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(); }; };

Here you go.干得好。 Firstly you getElementsByTagName that returns an HTMLCollection which you convert into an array using Array.prototype.slice .首先,您getElementsByTagName返回一个HTMLCollection ,您可以使用Array.prototype.slice将其转换为数组。 Then forEach child ie item in array, you .remove() it from DOM.然后对于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