Error when traveling with forEach

3

Why is it telling 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 does not WORK

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>
    
asked by Eduardo Sebastian 25.09.2017 в 12:15
source

4 answers

5

The problem is that document.getElementsByClassName does not return a Array , but an object HTMLCollection which, although very similar to an array, does not have any of the functions that the class Array has to traverse the elements.

One solution would be to "steal"%% of the Array from% to use on this object:

window.addEventListener("DOMContentLoaded", () => { 
 var i = document.getElementsByClassName('clases');
 Array.prototype.forEach.call(i,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>

What this code does is to run the method forEach of forEach , but assigning Array as context (the i within that function)

    
answered by 25.09.2017 / 12:21
source
3

The problem is that getElementsByClassName does not return a Array object, but a HTMLCollection that the forEach method does not have:

window.addEventListener("DOMContentLoaded", () => { 
 var i = document.getElementsByClassName('clases');
 for(var cont=0; cont < i.length; cont++){
  i.item(cont).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>
    
answered by 25.09.2017 в 12:23
2

As you have said above, you can not treat the object as an array, but you can extract the data from the object to be saved in one.

Array.from ()

The Array.from () method creates a new instance of Array from an iterable object.

window.addEventListener("DOMContentLoaded", () => { 
 var i = Array.from(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>

I leave here a link to the docu.

    
answered by 25.09.2017 в 12:32
1

I leave you an example working:

window.addEventListener("DOMContentLoaded", () => { 
 var i = document.getElementsByClassName('clases');
Array.prototype.forEach.call(i, function(elements, index) {
    elements.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>
    
answered by 25.09.2017 в 12:22