Loop for in getElementsByClassName

1

Why when I use for in to apply a rule to all elements of an html class through javascript until it works but does it always appear this error in the console?

TypeError: document.getElementsByClassName (...) [i] .style is undefined

var e = document.getElementsByClassName("minha-classe");

for (var i in e) {
  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>
    
asked by anonymous 12.07.2017 / 00:30

1 answer

2

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>
    
12.07.2017 / 00:58