0

So I have some JavaScript included in my HTML document, which just creates an array and writes the length of it in the Console:

var Bulbs = document.getElementsByClassName("Bulb");
console.log(Bulbs.length);

The output I get is 0, but when I type Bulbs.length directly in the Console, I get 2 as an output. Why is this so? My HTML code:

<header>
    <div class="Bulb nav">
        <a class="active">Hallo</a>
        <a>Hallo</a>
        <a>Hallo</a>
        <a>Hallo</a>
    </div>
    <div class="Bulb additional">
        <a>Impressum</a>
    </div>
</header>
Parzival
  • 2,051
  • 4
  • 14
  • 32
Sedoc
  • 13
  • 2
  • https://jsfiddle.net/un8o7cqr/ your code is working. returning 2 in the console. – Johnatha Relvas Apr 03 '21 at 19:22
  • You've to run the script after the page loaded. –  Apr 03 '21 at 19:23
  • `.getElementsByClassName` returns a live [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection). At the time you're logging the length in the console, there's no elements in the collection. Later, when you check the length of the collection, the body has been parsed, and the elements exist. – Teemu Apr 03 '21 at 19:23
  • @Teemu What do you mean by live? When I delete a matched element, the collection does not observe the deletion and continues with the same elements. –  Apr 03 '21 at 19:26
  • @Klaider Just read the linked MDN article ... The collection is live, and definitely a removed element is dropped from the live collection. See also https://stackoverflow.com/a/66480319/1169519 – Teemu Apr 03 '21 at 19:27
  • @Teemu I see, I was using `Node.prototype.querySelectorAll()`, which returns a `NodeList`, not a `HTMLCollection`. –  Apr 03 '21 at 19:32
  • Yep, that returns a static list. – Teemu Apr 03 '21 at 19:32
  • @Teemu , ok, and how can i fix this? Just adding a few seconds of wait to the start of my skript? – Sedoc Apr 03 '21 at 20:02
  • Nope, either add `defer` attribute to the script tag, or move the tag to the end of the `body`, or put your code in a `DOMContentReady` event handler. – Teemu Apr 03 '21 at 20:08

1 Answers1

0

Ok, so putting the script at the end of the body worked. Thanks @Teemu!

Teemu
  • 22,918
  • 7
  • 53
  • 106
Sedoc
  • 13
  • 2