简体   繁体   中英

HTML Collection length is 0 even after DOM has been rendered

I am working on SSR React-based application using NextJS . Once DOM has been rendered I need to detect a set of elements visibility in the viewport and once they are visible I need to do something. Now to accomplish that I need the reference to that set of elements which I am taking in componentDidMount lifecycle method, having an understanding that since DOM has been completely rendered I can grab all the elements together and watch them if they are in the viewport or not.

Below code is for taking the reference of the set of elements:

componentDidMount() {

    this.imageContainer = document.getElementsByClassName("prod_images");
    console.log('imageContainer -> ', this.imageContainer, 'length ->', 
    this.imageContainer.length, 'type is -> ', typeof this.imageContainer);
}

So, I get an HTMLCollection of a set of images which are stored in imageContainer variable. I did a console below and I get below in console :

在此处输入图片说明

In the above SS, I have only shown 4 entries from HTML Collection object, but I get all 141 correctly. My problem is that I am getting this.imageContainer.length as 0 in console, though the values are present. I use this.imageContainer.length, later on, to loop through the elements and at that time the value is 0.

Link -> Javascript HTML collection showing as 0 length explains the fact that this might be due to DOM elements are not loaded by that time and we should do this check in DOMContentLoaded . But I am already using componentDidMount lifecycle method. So what is the issue and why length is coming as 0. Is it got to do something with SSR?

As suggested in comment by epascarello

Because whatever is adding those elements is doing it after you read them. getElementsByClassName is a live Html Collection so as you add/remove things, it updates. That little [i] icon in the console is telling you it is updated

This is the right answer and solved my problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM