使用DOM方法循环属性
Loop through attributes using DOM methods?
我需要从节点列表中删除一些属性并保留一些属性。例如,有一个img
元素的列表,而您只需要src
和alt
属性,有什么方法可以循环遍历给定列表中元素的属性吗?
<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="">
您可以迭代每个元素的属性,在白名单中再次检查属性名称,并使用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);
}
}
}
相关文章:
- Javascript:循环属性内部的条件递增或递减
- 在循环中包含特定属性
- 借助for循环和数组在对象中添加属性
- 不可枚举的属性出现在 for..在 Chrome 中循环
- 我们可以设置属性'id'到不同的'按钮'通过使用javascript或jquery的循环
- 如何在循环中设置onclick属性
- 按数据属性循环元素并替换值
- 使用循环增加css属性值
- 循环浏览JavaScript对象并记录其属性
- ..的Javascript..循环中的对象没有在最后一个属性上运行
- 循环访问 JS 数组 + 数组属性
- 如何使用 jQuery 在循环中获取属性的值
- 为for循环中的对象添加新属性
- 在'用于'如果javascript中不存在对象属性,则循环
- Waypoint的循环,退出循环后属性未定义
- 如何循环对象中的javascript对象并查找属性
- 使用循环更新 JSON 属性值
- 未捕获的类型错误: 无法读取未定义的属性“循环”
- 使用点符号和括号显示..内部的属性..循环中
- 对象的正确属性循环