JavaScript Event Delegation

Example that illustrates event delegation and where it is useful.

by LyndseyB

HTML

Without Delegation:
<ul id="withoutDelegation">
  <li> Link 1 </li>
  <li> Link 2 </li>
  <li> Link 3 </li>
</ul>

<p>You clicked on item: <span id="resultWithoutDelegation"></span></p>


<br /><br />

With Delegation:

<ul id="withDelegation">
  <li> Link 1 </li>
  <li> Link 2 </li>
  <li> Link 3 </li>
</ul>

You clicked on item: <span id="resultWithDelegation"></span>

Babel + JSX

// without event delegation
const listWithoutDelegation = document.getElementById('withoutDelegation');
const resultWithoutDelegation = document.getElementById('resultWithoutDelegation');

Array.from(listWithoutDelegation.querySelectorAll('li')).forEach((li) => {
	li.addEventListener('click', (e) => {
  	resultWithoutDelegation.innerText = e.target.innerText;
  });
});

// ----------------
// what if we add another list item?
// ----------------
// const newItem = `<li> Link 4 </li>`;
// listWithoutDelegation.innerHTML += newItem;

const listWithDelegation = document.getElementById('withDelegation');
const resultWithDelegation = document.getElementById('resultWithDelegation');

// we assign the event listener to the parent element (UL)
listWithDelegation.addEventListener('click', (e) => {
	// since events bubble, we check that 
  // the clicked element was the LI
	if (e.target.nodeName === 'LI') {
  	resultWithDelegation.innerText = e.target.innerText;
  }
});

// ----------------
// what if we add another list item?
// ----------------
listWithDelegation.innerHTML += newItem;