Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Event Delegation in JavaScript

Learn event delegation in JavaScript: one parent listener for many children with event.target, matches() and closest(). Explanation and output.

IntermediateJavaScript Events ProgramsExample 4 of 10

This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add a <ul id="myList"> with <li> items, a #container div, and a #dataTable with rows that have data-id.

event-delegation.js
1// Method 1: Basic event delegation
2const list = document.getElementById('myList');
3
4// Instead of adding listener to each item
5list.addEventListener('click', function(e) {
6 if (e.target.tagName === 'LI') {
7 console.log('List item clicked:', e.target.textContent);
8 e.target.classList.toggle('active');
9 }
10});
11
12// Method 2: Dynamic content
13const container = document.getElementById('container');
14
15container.addEventListener('click', function(e) {
16 if (e.target.classList.contains('button')) {
17 console.log('Button clicked:', e.target.id);
18 }
19});
20
21// Add new buttons dynamically - they work automatically!
22function addButton(text) {
23 const btn = document.createElement('button');
24 btn.className = 'button';
25 btn.textContent = text;
26 container.appendChild(btn);
27}
28
29// Method 3: Multiple selectors
30container.addEventListener('click', function(e) {
31 if (e.target.matches('.delete-btn')) {
32 deleteItem(e.target.dataset.id);
33 } else if (e.target.matches('.edit-btn')) {
34 editItem(e.target.dataset.id);
35 } else if (e.target.matches('.view-btn')) {
36 viewItem(e.target.dataset.id);
37 }
38});
39
40// Method 4: Closest method
41container.addEventListener('click', function(e) {
42 const card = e.target.closest('.card');
43 if (card) {
44 console.log('Card clicked:', card.dataset.id);
45 }
46});
47
48// Method 5: Event delegation with data attributes
49const table = document.getElementById('dataTable');
50
51table.addEventListener('click', function(e) {
52 const row = e.target.closest('tr');
53 if (row) {
54 const id = row.dataset.id;
55 const action = e.target.dataset.action;
56
57 if (action === 'delete') {
58 deleteRow(id);
59 } else if (action === 'edit') {
60 editRow(id);
61 }
62 }
63});

Sample Output

Button clicked: (empty id)

addButton does not set an id, so e.target.id is an empty string.

In this one

  • Why one parent listener can handle many children
  • How event.target tells you what was clicked
  • How matches() and closest() find the right element
  • How data attributes carry ids and actions

How it works

  1. 1

    A click listener on #myList checks for LI targets.

  2. 2

    A #container listener checks for the button class.

  3. 3

    addButton creates new buttons that work without new listeners.

  4. 4

    matches() routes delete, edit and view buttons.

  5. 5

    closest() finds the parent card.

  6. 6

    The table listener reads data-id and data-action.

Edge cases

Clicking a child inside the target

Clicking a <span> inside an <li> gives target SPAN, so the tagName check fails.

Use e.target.closest("li") instead of checking tagName.

Placeholder functions

deleteItem is not defined.

Write your own deleteItem, editItem, viewItem, deleteRow and editRow before testing.

Events that do not bubble

Delegating focus does not work.

Use focusin, which bubbles.

What's going on

Event delegation means you put one listener on a parent element instead of one on every child. It works because clicks bubble up from the child to the parent. The parent then checks which child was clicked.

How it works: add the listener to the parent, look at event.target, and act based on what the target is. event.target is the exact element that was clicked.

Method 1 handles a list. The listener sits on the ul. If the clicked element's tagName is "LI", it logs the text and toggles an active class. One listener covers every item.

Method 2 shows the biggest benefit. Buttons added later with addButton() work automatically. They did not exist when the listener was added, but their clicks still bubble to the container. That is why delegation is ideal for dynamic content, like a to-do list where students add tasks.

Method 3 checks several kinds of buttons with matches(). matches('.delete-btn') returns true if the target fits that CSS selector. The functions deleteItem, editItem and viewItem are placeholders for your own code.

Method 4 uses closest('.card'). If you click an icon inside a card, the target is the icon, not the card. closest walks up from the target to find the nearest matching ancestor.

Method 5 uses data attributes. data-id on a row and data-action on a button give you the id and the action through dataset.

Benefits: it works with dynamic content, uses less memory, and needs a single listener, which helps performance. Use cases include dynamic lists, tables with actions, cards, and forms with dynamic fields. Best practices: use closest() for nested elements, check targets with matches(), and use data attributes for actions.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why does delegation work for elements added later?

Pick an answer to check it.

Question 2

What does closest(".card") return?

Pick an answer to check it.

Questions people ask

Does delegation make pages faster?

It uses fewer listeners and less memory, which helps on long lists.

What is dataset?

An object holding all data-* attributes. data-id becomes dataset.id.

When should I not use delegation?

For a single element, a direct listener is simpler.