To add event listeners to multiple elements in a single line with JavaScript, we can call addEventListener
on document
.
Then in the event handler, we can check which element is clicked.
For instance, we can write the following HTML:
<button>
button 1
</button>
<button>
button 2
</button>
<button>
button 3
</button>
<div>
not button
</div>
Then we can check if a button is clicked in the click event handler by writing:
document.addEventListener('click', (e) => {
if (e.target.tagName == "BUTTON") {
console.log('button clicked');
}
})
We use e.target.tagName
to get the tag name of the element that’s clicked.
Then we know a button is clicked if tagName
is 'BUTTON'
.
This works because JavaScript events propagate to ancestor elements by default.