Reputation: 13
I need to remove some attributes and preserve some from a list of nodes. For instance, there is a list of img
elements and you just need src
and alt
attributes, is there any way to loop through attributes of elements in a given list?
<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="">
Upvotes: 1
Views: 134
Reputation: 318182
You can iterate over the attributes for each element, check the name of the attribute agains a white-list, and remove anything else using 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);
}
}
}
Upvotes: 3