NodeList length is shown 1 even though there are 3 elements

Hello All,

Happy New Year !

I have the following code:

       let htmlCollection  =  document.getElementsByClassName('p-fileupload-content');   

        console.log("Printing HTMLCollection");


        console.log("Printing HTMLCollection childNodes");


        console.log("Printing HTMLCollection childNodes length");

  1. console.log(htmlCollection); prints the following:

HTMLCollection { 0: div.p-fileupload-content, length: 1 }

  1. console.log("Printing HTMLCollection childNodes"); prints following:

NodeList [ div ]
0: <div class="p-progressbar p-componen…progressbar-determinate" role="progressbar" aria-valuemin="0" aria-valuemax="100">
1: <div>
2: <div class="p-fileupload-files">
length: 3

<prototype>: NodeListPrototype { item: item(), keys: keys(), values: values(), … }
  1. However console.log("Printing HTMLCollection childNodes length"); prints 1 even though the length shown in the second console log above is 3. I want to access the 2: <div class="p-fileupload-files"> of the nodelist and traverse deep down to attach an event listner to some other childNode element. What am I doing wrong here?

Hi @Jack_Tauson_Sr, a happy new year to you too! :-)

Hm that first line in the console output does indeed suggest that the node list only has a single div child… could you post a fiddle so we can check the console ourselves?

3 is the length the HTMLcollection nodeList
1 is the length of the HTMLcollection[0] node.

IKt would help if the html it was targeting was shown.

Hi @m3g4p0p , Thanks for your wishes and your inputs.

It’s coming from 1700 lines of code so I will try to see if I am able to generate a fiddle based off of that.

I was wondering since I am using getElementsByClassName , so this returns live HTML collection. So if I want to modify something based off of this live collection , is it something doable or is getElementsByClassName just for seeing live HTML collection in console log only?

Thank you, @dennisjn. That makes sense. If I have to select 2: <div class="p-fileupload-files"> (basically, 3rd nodelist from the HTML collection), what would be the correct way to go about it?

Yes everything in a live nodelist can be modified. It just means that any changes will be seen in the nodelist and so you don’t need to do another getElementsByClassName to see the change.

You could use

let html_item_3  =  document.getElementsByClassName('p-fileupload-content')[2];

to select the third item.
The collection index is zero based.

Thanks. html_item_3 is printing undefined in console log.