0

I am trying to go through all elements when I use getElementsByClassName function but I notice that I am getting length equals to 0.

This is my simple example:

index.html

<html>
    <head>
        <script type="text/javascript" src="prove.js"></script>
    </head>
    <body>
        <button class="cButton">1</button>
        <button class="cButton">2</button>
        <button class="cButton">3</button>
        <button class="cButton">4</button>
        <button class="cButton">5</button>
        <button class="cButton">6</button>
    </body>
</html>

prove.js

var buttons = document.getElementsByClassName("cButton");
console.log(buttons);
console.log("Length: " + buttons.length);

I am confused because this is the result obtained on the console:

enter image description here

So if the HTMLCollection have results, why am I getting length equals to 0?

Nevertheless, if I execute the same code on a snippet here, it shows the real length:

var buttons = document.getElementsByClassName("cButton");
console.log(buttons);
console.log("Length: " + buttons.length);
<button class="cButton">1</button>
<button class="cButton">2</button>
<button class="cButton">3</button>
<button class="cButton">4</button>
<button class="cButton">5</button>
<button class="cButton">6</button>

Why on my example I cannot get the real length of the HTMLCollection if it is filled?

Thanks in advance!

Francisco Romero
  • 11,900
  • 18
  • 71
  • 151
  • 2
    Try putting your ` – Blorgbeard Nov 29 '17 at 23:11
  • 1
    The duplicate offers solutions but not an answer to the question. The issue is because you're getting a "live list" and doing so before the elements exist. So when you check its `.length`, there are none there, but by the time you view the console, the elements have been loaded. –  Nov 29 '17 at 23:12
  • @rockstar So, do you mean that it is being executed the second console log before than the first one? – Francisco Romero Nov 29 '17 at 23:15
  • @Error404 your JavaScript code is positioned in the document **before** the elements it's trying to find. If you put its ` – Pointy Nov 29 '17 at 23:17
  • @Blorgbeard Thanks! It works! But what if I want to have all my js grouped at header? Should I put all of them after the body? – Francisco Romero Nov 29 '17 at 23:19
  • 1
    @Error404: No, they're executed in order, both immediately. But the list gets populated after the elements appear, and the console shows the updated list even though it was empty when you logged it. –  Nov 29 '17 at 23:21
  • @Error404 you could subscribe to the `window.load` event: https://developer.mozilla.org/en-US/docs/Web/Events/load – Blorgbeard Nov 30 '17 at 00:29

0 Answers0