[英]Javascript html dom elements array for in loop
所以说我有一个DOM元素数组:
var z = document.getElementsByClassName('name');
并为我要在for循环中设置属性的每个元素:
for(var n in z){z[n].setAttribute('marked', '1');}
对于上面的代码,我得到z[n].setAttibute is not a function
。 但是,当我手动签入z数组的控制台元素时,已将marked
属性添加到每个元素。 为什么会发生这种情况,如何防止这种错误发生?
document.getElementsByClassName
返回HTMLCollection的实例, HTMLCollection是一个类似数组的对象。 for..in
循环是为对象而不是数组设计的。 它遍历对象的所有属性。 因此,在遍历HTMLCollection时,除了数组索引之外,您还可以获得其他属性,例如length
。 由于length
只是一个数字,因此没有setAttribute
方法,因此会出现该错误。
您应该使用常规的for
循环,或for..of
循环:
const z = document.getElementsByClassName('name')
// Regular loop:
for (let i = 0, len = z.length; i < len; i++) {
z[i].setAttribute('marked', '1')
}
// for..of loop:
for (const element of z) {
element.setAttribute('marked', '1')
}
您还可以使用Array.from()
将HTMLCollection转换为数组。 然后,您可以在其上使用所有数组方法,例如.forEach()
:
const z = Array.from(document.getElementsByClassName('name'))
z.forEach(element=> element.setAttribute('marked', '1'))
[].forEach.call(z, function(el) {
el.setAttribute('marked', '1');
})
for..in将获取HTMLCollection的所有键,包括属性.length。 .length是一个数字,没有.setAttribute函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.