Add event listener to multiple buttons with the same class
Mon Jun 29 2020 23:11:09 GMT+0000 (UTC)
Saved by @mishka #javascript
This works for an array of elements with the same class.
example.comMon Jun 29 2020 23:11:09 GMT+0000 (UTC)
Saved by @mishka #javascript
This works for an array of elements with the same class.
example.com
Comments
Anonymous - Sat Mar 20 2021 06:06:43 GMT+0000 (UTC)
TYSM!
You should declare the named handler function first, like «function myHandler () { /* ... */ }» and then attach it inside the loop by name - «Array.from(document.getElementsByClassName('saveBtn')).forEach(function (elm) { elm.addEventListener('click', myHandler) })». Avoid using anonymous functions this way 'cause for each element in loop you force the browser engine to create new function instance (the same anonymous function) from scratch again and again. Moreover, anonymous functions cannot be detached from listeners