skip to Main Content

I am trying to iterate over the object returned by document.getElementsByClassName(). The returned object contains three elements with the specified class name. However, when I try to access each element using the for loop, the object acts as if it is empty with 0 length.

Here are the console logs I did in an attempt to debug.

First I logged the object returned.

elements = document.getElementsByClassName("brute-force-effect");
console.log(elements);

Output

> HTMLCollection []
  > 0: div.tile.brute-force-effect.harsh
  > 1: div.tile.brute-force-effect.kaso
  > 2: div.name.brute-force-effect
> length: 3
> [[Prototype]]: HTMLCollection

Clearly, it contains all three elements. However, when I logged its length

console.log(elements.length);

Output

0

I tried iterating over it as follow

for (e of elements) {
    console.log(e);
}

Output

No output

And since elements.length returns 0, following method, as provided in the solution to a similar stackoverflow question doesn’t work either.

for (i = 0; i < elements.length; i++) {
    console.log(elements.item(i));
}

Output

No output

2

Answers


  1. Are you executing your code within the following scope?

    document.addEventListener("DOMContentLoaded", function() {
        // Your code here
    });
    Login or Signup to reply.
  2. I think the reason why you are unable to iterate over the object returned by document.getElementsByClassName() is because it is an HTMLCollection, not an Array. An HTMLCollection is a live object, which means that it changes as the DOM changes. This can be a problem when you are trying to iterate over an HTMLCollection, because the length of the collection may change while you are iterating over it.

    To fix this, you need to convert the HTMLCollection to an Array. You can do this using the Array.from() method. The following code will do this:

    const elements = document.getElementsByClassName("x");
    const elementsArray = Array.from(elements);
    
    for (const element of elementsArray) {
      console.log(element);
      element.innerHTML = "new text";
    }
    <html>
      <body>
        <div class="x">1</div>
        <div class="x">2</div>
        <div class="x">3</div>
        <div class="x">4</div>
        <script src="index.js"></script>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search