HTML Collection length is 0 even after DOM has been rendered

回眸只為那壹抹淺笑 提交于 2020-04-16 02:28:12

问题


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?

来源:https://stackoverflow.com/questions/60601380/html-collection-length-is-0-even-after-dom-has-been-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!