HTMLCollection and Nodelist on() - KirkGarcia182/domExtend GitHub Wiki

on()

Description

Adds an event listener to all the elements within the collection. The syntax is the same as addEventListener. You can access the index of the element within the collection just pass a second parameter in the listener function.

Syntax

collection.on(type, listener[, options]);

Return Value

The collection you just manipulated so you can chain these methods.

Example

<!DOCTYPE html>
<html>
<head>
	<title>domExt Examples</title>
</head>
<body>
	<div id="app">
		<div class="menus">
			<ul id='menuList1'>
				<li><a class='menuLink'>Menu 1</a></li>
				<li><a class='menuLink'>Menu 2</a></li>
				<li><a class='menuLink'>Menu 3</a></li>
			</ul>
			<ul id="menuList2"></ul>
			<ul id="menuList3"></ul>
		</div>
	</div>
	<script type="text/javascript" src="domExt.js"></script>
	<script type="text/javascript">
		window.$ = document;

		let collection = $.qsa('.menuLink');
		collection.on('click', (event, index) => {
			alert(`Menu ${index+1} was clicked`);
                        console.log(collection[index]);
		});

		/*
			Clicking on Menu 1 will alert "Menu 1 was clicked" and log "<a class='menuLink'>Menu 1</a>" in the developers console
			Clicking on Menu 2 will alert "Menu 2 was clicked" and log "<a class='menuLink'>Menu 2</a>" in the developers console
			Clicking on Menu 3 will alert "Menu 3 was clicked" and log "<a class='menuLink'>Menu 3</a>" in the developers console
		*/
	</script>
</body>
</html>
⚠️ **GitHub.com Fallback** ⚠️