2016-08-05 53 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); 
     } 

    } 
}