The return of getElementsByClassName
is an object of the type HTMLCollection
, not just an object NodeList
. This object has a read-only attribute called length
and so-called methods item
and namedItem
which are included in the iterations when using the for
. To check, simply 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 value length
is assigned to the variable i
, because the code tries to define the style of an element e[length]
, but this is not an HTML element. To get around the problem, simply change the repetition 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>
So you ensure that the values of i
shall always be valid and shall pass through all elements of the list.
Using the for ... of
Using ES6 it is possible to use the 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>
Thanks for the answer, it helped a lot. I was trying to understand for a while why this happened.
– user83428