![](/img/trans.png)
[英]How can i remove all div's and other DOM HTML elements except a particular class using jQuery
[英]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.