2016-08-05 54 views
1

我需要删除一些属性并保留一些节点列表。例如,有一个img元素的列表,你只需要srcalt属性,是否有任何方式来循环给定列表中的元素的属性?使用DOM方法遍历属性?

<img src="" alt="" height="" width="" class="class1"> 
<img src="" alt="" height="" width="" class="class2"> 
<img src="" alt="" height="" width="" class="class3"> 
<img src="" alt="" height="" width="" class="class4"> 
<img src="" alt="" height="" width="" class="class5"> 
<img src="" alt="" height="" width="" class="class6"> 
<img src="" alt="" height="" width="" class="class7"> 
<img src="" alt="" height="" width="" class="class8"> 
<img src="" alt="" height="" width="" class="class9"> 
<img src="" alt="" height="" width="" class="class10"> 

<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
<img src="" alt=""> 
+0

删除任何东西是所提供的代码的两个部分,即在第一块是什么存在,第二块是想要的结果?也许第一块是“给定清单”。使用元素ID可能是有利的(例如,如果它们在DIV中),那么您可以获得DIV元素并循环通过子节点。例如'c = document.getElementById(AC_ChildDiv); \t \t(i = 0; i MikeT

+0

欢迎计算器!提供其他详细信息[使这个更好的问题](http://stackoverflow.com/help/how-to-ask):列出你已经尝试过,在互联网上进行研究,并告诉我们,虽然明显的解决方案没有工作。快速谷歌搜索会调出[jquery .removeAttr()](https://api.jquery.com/removeAttr/)方法,这看起来非常完美。 – emunsing

回答

3

可以遍历每个元素的属性,检查属性的名称agains白名单,并且使用removeAttribute()

var images = document.querySelectorAll('img'); 

for (var i = images.length; i--;) { 
    for (var j = images[i].attributes.length; j--;) { 

     var attribute = images[i].attributes[j]; 

     if (['src', 'alt'].indexOf(attribute.name) === -1) { 
      images[i].removeAttribute(attribute.name); 
     } 

    } 
}