Loop for in in getElementsByClassName

Asked

Viewed 270 times

1

Why when I use for in to apply a rule to all elements of an html class through javascript it even works but always appears 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>

1 answer

2


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.