javascriptloopsiteratorgetelementsbyclassname

Unable to iterate over document.getElementsByClassName()


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

Solution

  • Are you executing your code within the following scope?

    document.addEventListener("DOMContentLoaded", function() {
        // Your code here
    });