The method document.getElementsByClassName()
returns and HTMLCollection wich is an array-like object (but not an array), so you can't use forEach()
on it to iterate over his elemtents. Instead, you can use a for loop:
let h = document.getElementsByClassName("buttons");
for (let i = 0; i < h.length; i++)
{
h[i].addEventListener("click", function()
{
alert(this.id);
});
}
<button id="id1" class="buttons">BUTTON 1</button>
<button id="id2" class="buttons">BUTTON 2</button>
Alternatively, you can spread
his element on an array, and then use forEach()
on it:
let h = document.getElementsByClassName("buttons");
[...h].forEach(function(btn)
{
btn.addEventListener("click", function()
{
alert(this.id);
});
});
<button id="id1" class="buttons">BUTTON 1</button>
<button id="id2" class="buttons">BUTTON 2</button>