KOMPX.COM or COMPMISCELLANEA.COM   

Add an event listener to multiple different elements at once (JavaScript)

How to add an event listener to multiple different elements at once in JavaScript.

The click event handling is added to more than one element at the same time (to both button and span). So that clicking on any will change the example box background:

Span

HTML code:


<div class="example">
	<button>Button</button>
	<span>Span</span>
</div>

JavaScript code:


<script>
var button = document.querySelector('.example button');
var span = document.querySelector('.example span');

[button, span].forEach( function ( element ) {
	element.addEventListener('click', function () {
		this.closest('.example').classList.toggle('background-red');
	});
});
</script>

Browser support

Windows
Edge 15.0+
Firefox 35.0+
Google Chrome 41.0+
Opera 28.0+
Linux
Firefox 35.0+
Google Chrome 41.0+
Opera 28.0+
iOS
Safari 9.0+
Android
Samsung Internet 4.0+
Chrome Android 41.0+
Firefox for Android 35.0+
Opera Android 28.0+

More