Why does it tell me that forEach is not a function?
What I do is get the elements with class 'classes' and then assign each one an onclick event, but it doesn't WORK for me
window.addEventListener("DOMContentLoaded", () => {
var i = document.getElementsByClassName('clases');
i.forEach(e => {
e.onclick = () => {alert('BonApetit');};
});
});
<a class="clases">Enlace 1</a>
<a class="clases">Enlace 2</a>
<a class="clases">Enlace 3</a>
<a class="clases">Enlace 4</a>
The problem is that
document.getElementsByClassName
it doesn't return aArray
, but an objectHTMLCollection
that, although it is very similar to an array, does not have any of the functions that the classArray
has to iterate through the elements.One solution would be to "steal"
Array
the functionforEach
to use it on this object:What this code does is execute the method
forEach
,Array
but assigning iti
as a context (thethis
inside that function)The problem is that
getElementsByClassName
it does not return an objectArray
but oneHTMLCollection
that does not have the methodforEach
:As you have been told above, you cannot treat the object as an array, but you can extract the data from the object to save them in one.
Array.from()
The Array.from() method creates a new Array instance from an iterable object.
Here is a link to the document.
I leave you an example working: