gpt4 book ai didi

javascript - 如何删除包含除特定属性之外的所有属性的标签

转载 作者:行者123 更新时间:2023-12-01 04:04:26 25 4
gpt4 key购买 nike

这是我的代码:

var str = `<p>paragraph<a>link</a></p>
<div class="myclass">
<div>something</div>
<div style="mystyle">something</div>
<b><a href="#">link</a></b>
<b><a href="#" name="a name">link</a></b>
<b style="color:red">bold</b>
<img src="../path" alt="something" />
<img src="../path" alt="something" class="myclass" />
</div>`;
var div = document.createElement("div");
div.innerHTML=str;
div.querySelectorAll("*").forEach(function(el){
for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++){
var att = atts[i].nodeName;
if (["src","alt","href"].indexOf(att) ==-1) el.removeAttribute(att);
}
});
// console.log(div); alert shows it more clearly
alert(div.innerHTML);

它会删除除 src 之外的所有属性, alt , href 。现在我想删除标签(不仅仅是属性),它包含除这三个属性之外的任何属性。

我已经测试过removeChild()而不是removeAttribute() ,但它没有按预期工作。有什么想法吗?

<小时/>

一个简短的例子:

输入:

<a href="#" class="sth">link</a>
<img src="#" />

预期输出:

link
<img src="#" />

<a>应该删除,因为 class属性。

最佳答案

var str = `<p>paragraph<a>link</a></p>
<div class="myclass">
<div>something</div>
<div style="mystyle">something</div>
<b><a href="#">link</a></b>
<b><a href="#" name="a name">link</a></b>
<b style="color:red">bold</b>
<img src="../path" alt="something" />
<img src="../path" alt="something" class="myclass" />
</div>`;
var div = document.createElement("div");
div.innerHTML=str;
div.querySelectorAll("*").forEach(function(el){
for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++){
var att = atts[i].nodeName;
if (["src","alt","href"].indexOf(att) ==-1){
var parent = el.parentElement;
while(el.firstChild) parent.insertBefore(el.firstChild, el);
parent.removeChild(el);
break; // element is already removed, don't loop over attributes of a removed element.
}
}
});
// console.log(div); alert shows it more clearly
alert(div.innerHTML);

关于javascript - 如何删除包含除特定属性之外的所有属性的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41939651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com