Search code examples
reactjsfor-loophtmlcollection

Iterating through HTMLcollection in React,js


I am having trouble iterating through and HTMLCollection in a React.js component. I have the following function:

shuffleLists = () => {
        var elems = document.getElementsByTagName("ul");
        console.log(elems)

        for (let item of elems) {
          console.log(item);
        }   
    }

console.log(elems) prints out an HTMLCollection of ul elements as expected. But the for loop after it doesn't print anything in the console, when I would expect to see each ul element printed in the console. What am I doing wrong?

Edit for clarity:

The key issue here is that the line console.log(item) inside the loop does not output anything into the console in chrome dev tools, and the same applies to other various loop syntaxes as discussed in the answers and comments below.

I also have noticed that there is different lengths being logged from console.log(elems) between different browsers. In chrome I see HTMLCollection[] length: 10 ... But in Firefox I see HTMLCollection {length 0} ...


Solution

  • I figured out my problem was that I was calling the shuffleLists function from the parent component in React, prior to the ul and li elements I wanted to iterate through being rendered in the sub-component. The console output for the elems var was confusing as it showed all the lists and list items inside the HTMLCollection.

    When I moved the shuffleLists function to the sub-component and called it inside componentDidMount I was able to loop through and console out all the list items as desired.