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:
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!

<script>at the bottom of your<body>, after the buttons have been loaded..length, there are none there, but by the time you view the console, the elements have been loaded.<script>tag at the end of the body, it will work as you expect.