gpt4 book ai didi

用于循环的Javascript html dom元素数组

转载 作者:行者123 更新时间:2023-11-30 15:58:13 25 4
gpt4 key购买 nike

假设我有一个 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。但是,当我手动 checkin z 数组的控制台元素时,marked 属性已添加到每个元素。为什么会发生这种情况?如何防止此类错误发生?

最佳答案

document.getElementsByClassName 返回 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'))

关于用于循环的Javascript html dom元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38174179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com