Here is my code:
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);
It removes every attribute except src
, alt
, href
. Now I want to remove the tag (not just the attribute) which contains any attribute except those three ones.
I've tested removeChild()
instead of removeAttribute()
, but it doesn't work as expected. Any idea?
An short example:
input:
<a href="#" class="sth">link</a>
<img src="#" />
expected output:
link
<img src="#" />
<a>
should be removed, because of class
attribute.