JavaScript JavaScript and the DOM Getting a Handle on the DOM Select All Elements of a Particular Type

meghana Joshi
meghana Joshi
4,547 Points

I tried to use the forEach method and it does not work

const mylist = document.getElementsByTagName('li');
mylist.forEach(item =>item.style.color = 'purple');

I am getting an error forEach is not a function. Can anyone explain me why it does not work?

1 Answer

Alfonso Montano
Alfonso Montano
2,969 Points

The reason is because document.getElementsByTagName returns an HTMLCollection not an array

To solve this you can use ES6 Array.from method

Try this:

const mylist = document.getElementsByTagName("li");

Array.from(mylist).forEach(item => {
    item.style.color = "purple";
});
meghana Joshi
meghana Joshi
4,547 Points

thanks that worked. I also tried

const mylist = document.querySelectorAll('li');
mylist.forEach(item => item.style.color = "red");

which also worked