Javascript html dom 循环中的元素数组
Javascript html dom elements array for in loop
假设我有一个包含 DOM 个元素的数组:
var z = document.getElementsByClassName('name');
对于每个我想用 for in 循环设置属性的元素:
for(var n in z){z[n].setAttribute('marked', '1');}
对于上面的代码,我得到 z[n].setAttibute is not a function
。但是,当我手动签入 z 数组的控制台元素时,marked
属性已添加到每个元素。为什么会发生这种情况,如何防止此类错误发生?
[].forEach.call(z, function(el) {
el.setAttribute('marked', '1');
})
for..in 将获取 HTMLCollection 的所有键,包括 属性.length。 .length 是一个数字,没有 .setAttribute 函数。
document.getElementsByClassName
returns 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()
. Then you can use all array methods on it, for example .forEach()
:
将 HTMLCollection 转换为数组
const z = Array.from(document.getElementsByClassName('name'))
z.forEach(element=> element.setAttribute('marked', '1'))
假设我有一个包含 DOM 个元素的数组:
var z = document.getElementsByClassName('name');
对于每个我想用 for in 循环设置属性的元素:
for(var n in z){z[n].setAttribute('marked', '1');}
对于上面的代码,我得到 z[n].setAttibute is not a function
。但是,当我手动签入 z 数组的控制台元素时,marked
属性已添加到每个元素。为什么会发生这种情况,如何防止此类错误发生?
[].forEach.call(z, function(el) {
el.setAttribute('marked', '1');
})
for..in 将获取 HTMLCollection 的所有键,包括 属性.length。 .length 是一个数字,没有 .setAttribute 函数。
document.getElementsByClassName
returns 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()
. Then you can use all array methods on it, for example .forEach()
:
const z = Array.from(document.getElementsByClassName('name'))
z.forEach(element=> element.setAttribute('marked', '1'))