【问题标题】:How can I remove html elements that are nested into each other?如何删除相互嵌套的 html 元素?
【发布时间】:2021-12-23 17:59:47
【问题描述】:

我有一个这样的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 循环不起作用。

任何帮助表示赞赏。

【问题讨论】:

  • 一个 sn-p 只有在有一些可以执行的东西并且为问题添加一些有用的东西时才有意义。在这种情况下,它需要一个“正确的”sn-p (-> I've been told to create a "runnable" example with "Stack Snippets", how do I do that?)。否则使用简单的代码块。
  • “描述问题。“它不起作用”不足以帮助人们理解你的问题。相反,告诉其他读者预期的行为应该是什么。告诉其他读者错误消息的确切措辞是什么,以及产生错误消息的代码行。使用简短但描述性的问题摘要作为问题的标题。"

标签: javascript html vue.js ecmascript-6


【解决方案1】:

我自己解决了,很简单。

我不得不做一个递归函数。

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

【讨论】:

  • 您创建了一个removeChildComponents 方法,这似乎只是它的主体。请在递归引用时发布整个方法(带有签名)。
【解决方案2】:

给你。首先你getElementsByTagName返回一个HTMLCollection,你使用Array.prototype.slice将它转换成一个数组。然后 forEach 子元素,即数组中的项目,你 .remove() 它来自 DOM。

Array.prototype.slice.call(document.getElementsByTagName('child')).forEach(child =&gt; 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>

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2013-11-22
    • 2014-05-03
    • 2017-06-03
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多