Home > Software design >  Javascript length variable displaying zero
Javascript length variable displaying zero

Time:06-10

can you please look at the image below and let me know what would lead to this? The console shows that the variable playIcons has 3 items in it's array. then I'm declaring x = playIcons.length. (FYI - I tested it with several other variable names to make sure that the name wasn't causing the issue.) However x generates as zero, but when I put playIcons.length I receive the correct total. (3). Also, FYI, this is global.(not inside of a function)

Please let me know what leads to this so I can avoid it going forward.enter image description here

CodePudding user response:

You have not provided a way to reproduce your problem, so I offer this working example as a counterexample and a guide to correct usage.

let playIcons = document.getElementsByClassName("fa-play");
let x = playIcons.length;
console.log('x is', x);
<div >A</div>
<div >B</div>
<div >C</div>

CodePudding user response:

We certainly can't know what is causing this, because you haven't provided a minimal, reproducible example. But if the question is what could cause this...

getElementsByClassName returns an HTMLCollection, which is a live collection of elements and is automatically updated when the underlying DOM changes. So playIcons may have changed between the time you first measured it's length and the time you next measured its length.

For example:

let coll = document.getElementsByClassName('live');
let x = coll.length;
console.log('x: ', x);

let el = document.createElement('span');
el.classList.add('live');
document.getElementById('test').appendChild(el);

// Note: coll was never re-assigned or modified by me
let y = coll.length;
console.log('y: ', y);
<div id="test"></div>

  • Related