且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何删除除特定标签以外的所有标签的属性?

更新时间:2023-11-14 09:25:16

var str =`< p>段落< a>链接< / a>< / p>< div class =myclass>< div>东西< / div>< div style =mystyle >东西< / div>< b>< a href =#>链接< / a>< / b>< b>< a href =#name =a name > link< / a>< / b>< b style =color:red> bold< / b>< img src =../ pathalt =something/><一世mg src =../ pathalt =somethingclass =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:显示它更清晰(div.innerHTML);

请注意,您需要反引号引用嵌入换行符的字符串

I have this string:

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>';

I want to remove all attributes except href, src, alt. So this is expected result:

/* 
<p>paragraph<a>link</a></p>
<div>
    <div>something</div>
    <div>something</div>
    <b><a href="#">link</a></b>
    <b><a href="#">link</a></b>
    <b>bold</b>
    <img src="../path" alt="something">
    <img src="../path" alt="something">
</div>

How can I do that?


I can just select them which isn't useful:

/<[a-z]+ .*?(href|src|alt)="[^"]+"/g

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

PS: Please note that you need backticks to quote a string with embedded newlines