The return of getElementsByClassName
is an object of type HTMLCollection
, not just a NodeList
object. This object has a read-only attribute called length
and methods named item
and namedItem
that are included in iterations when for
is used. To check, just display the value of i
:
var e = document.getElementsByClassName("minha-classe");
for (let i in e) {
console.log(i);
}
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
The error is generated when the length
value is assigned to the i
variable, because the code tries to set the style of a e[length]
element, but this is not an HTML element. To work around the problem, simply change the repeat structure:
var e = document.getElementsByClassName("minha-classe");
for (let i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
This ensures that the values of i
will always be valid and will scroll through all the elements of the list.
Using for ... of
Using ES6, you can use for ... of
instead of for ... in
. See the example below:
var e = document.getElementsByClassName("minha-classe");
for (let i of e) {
i.style.display = "none";
}
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>
<div class="minha-classe">...</div>