DEV Community

GreggHume
GreggHume

Posted on

Simplest way to loop node list / HTMLCollection using map, foreach etc

You spread the list like this:

const elements = document.getElementsByClassName('modal');

[...elements].forEach((element)=> {
  console.log(element)
})
Enter fullscreen mode Exit fullscreen mode

Or in one line like this, this is useful if you are doing multiple loops and do not want to spread every time:

const elements = [...document.getElementsByClassName('modal')];

elements.forEach((element)=> {
  console.log(element)
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)