How do I add an event listener to multiple buttons and get the value of each one depending on the one clicked. Eg:
<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>
So that on javascript, I wouldn't have to reference each button like:
Const but1 = document.getElementById('but1');
but1.addEventListener('click');
Adding an Event Listener to Multiple Elements Using a for...of Loop + IIFE. Open the console and click any of the buttons. The same event listener is added to each button using a for...of loop along with an immediately invoked function that passes the current element of the loop back into the function.
To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.
We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
You don't really need to add listeners to all the buttons. There is such thing in JS as Bubbling and capturing so you can wrap all your buttons
with a div
and catch all the events there. But make sure you check that the click was on a button
and not on the div
.
const wrapper = document.getElementById('wrapper');
wrapper.addEventListener('click', (event) => {
const isButton = event.target.nodeName === 'BUTTON';
if (!isButton) {
return;
}
console.dir(event.target.id);
})
div {
padding: 20px;
border: 1px solid black;
}
<div id='wrapper'>
<button id='but1'>
Button1
</button>
<button id='but2'>
Button2
</button>
<button id='but3'>
Button3
</button>
<button id='but4'>
Button4
</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With