var how_many = document.getElementsByClassName("content"); console.log(how_many); 

With this code, the object is displayed:

HTMLCollection []

0: div.content

1: div.content

2: div.content

3: div.content

length: 4

proto : HTMLCollection

If we change the code to the following:

 var how_many = document.getElementsByClassName("content").length; console.log(how_many); 

That in the console appears 0.

Even if we summarize:

 var how_many = document.getElementsByClassName("content"); console.log(how_many); console.log(how_many.length); 

That is displayed as that object, and zero.

Why?

  • probably somewhere in the code you override a variable or problem in scope. Generally need the full code - DemoGosha
  • I do not know if browsers HTMLCollection when a new suitable element appears on the page, but if they update, everything is simple: the browser console usually shows the state of the object at the current moment, and not at the time you called console.log . And if your div.content is not div.content yet by the time you called console.log , then when outputting such a collection it will be 0 , although if you print the collection itself, then it will have a non-zero length. - selya
  • Added a question, maybe it will help - igor_bal

1 answer 1

Here everything is clear and correct:

 <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <script> var how_many = document.getElementsByClassName("content"); console.log(how_many.length); console.log(how_many); </script> 

But what you have:

 <div id="out1"></div> <div id="out2"></div> <script> var how_many = document.getElementsByClassName("content"); document.getElementById("out1").innerText = how_many.length; setTimeout(function() { document.getElementById("out2").innerText = how_many.length; }, 100); </script> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> 

That, too, in general, is understandable and correct.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

An HTMLCollection in the HTML DOM is live; it is automatically updated when the document is changed.

... the collection is automatically updated to reflect changes in the document.