document.getElementsByClassName
returns an instance of HTMLCollection, an array-like object. for..in
loop was designed for objects, not arrays. It iterates through all properties of an object. Therefore, when iterating through HTMLCollection, besides array indexes you get also other properties, like length
. As length
is simply a number, it doesn't have setAttribute
method, so you get that error.
You should either use a regular for
loop, or for..of
loop:
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')
}
You can also convert HTMLCollection to array using 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'))