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!

7
  • 2
    Try putting your <script> at the bottom of your <body>, after the buttons have been loaded. Commented Nov 29, 2017 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. Commented Nov 29, 2017 at 23:12
  • @rockstar So, do you mean that it is being executed the second console log before than the first one? Commented Nov 29, 2017 at 23:15
  • @Error404 your JavaScript code is positioned in the document before the elements it's trying to find. If you put its <script> tag at the end of the body, it will work as you expect. Commented Nov 29, 2017 at 23:17
  • 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. Commented Nov 29, 2017 at 23:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.