Open up Open up - 1 month ago 7
Javascript Question

Working code brings error addEventListener is not a function

I use this code:

for (el in document.getElementsByClassName("close-sidenav"))
document.getElementsByClassName("close-sidenav")[el].addEventListener("click", closeSidenav);


and it works perfectly, it adds click event on elements, but Chrome keeps telling me this:


Uncaught TypeError: document.getElementsByClassName(...)[el].addEventListener is not a function(…)

How do I prevent Chrome from giving me an error on working code?

Answer

document.getElementsByClassName() returns an HTMLCollection object.

That object has numeric properties, but also has other properties that will be included in a for/in enumeration.

So, don't use for/in with the HTMLCollection returned by document.getElementsByClassName() because it will return other properties of that data structure that are not the elements you want.

Instead, use a regular for loop.

var list = document.getElementsByClassName("close-sidenav");
for (var i = 0; i < list.length; i++) {
    list[i].addEventListener("click", closeSidenav);
}

See this other answer foreach loop for HTMLCollection elements for many more details including cool ways to do this iteration in ES6 using Array.from() or ways to use for/of loops.