javascript - How can I remove html elements that are nested into each other?
问题描述
I have an html structure like this:
<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:
<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.
Any help appreciated.
解决方案
我自己解决了它,这很容易令人尴尬。
我不得不做一个递归函数。
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();
};
};
推荐阅读
- javascript - 使用 forEach 循环分解函数
- reactjs - 从子组件更新 React 上下文
- github-actions - 依赖机器人:错误:.github#L1 `on` 中没有定义事件触发器
- outlook-redemption - Outlook 365 的 RDO 规则问题
- firefox - 如何拦截 Playwright 的 Firefox 图片请求
- javascript - 通过循环一个 javascript 对象来创建元素
- xcode - Xcode 13 AppleScript 框架无法将 UI 连接到 Applescript 代码
- odoo - 如何通过不同模型中的创建功能自动将新记录添加到 One2Many 字段?
- python - Python xml.etree.ElementTree.ParseError 从 XML 转换为 CSV
- javascript - 使用网格布局将填充调整到中心页面