Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.3 — Event Delegation
JavaScript · Example 1 of 3

A to-do list with one listener

Item 3 was created after the listener, yet its ✓ button works. The click on the text was ignored because closest("[data-action]") returned null.

Event delegation means putting one listener on a parent instead of one on every child: because events bubble, the parent hears every child's event, uses event.target.closest() to find which child it was, and automatically handles children added later.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given <div id="tabs"><button data-tab="home">Home</button><button data-tab="news">News</button></div>, write one listener that logs open home or open news. Click News from code.

02

Write a delegated listener on a <table id="grid"> that logs the text of the row (<tr>) whose cell was clicked, and ignores clicks on the <thead>.

Explain it without notes

01

What is event delegation and why does it work?

02

Why do you need closest in a delegated listener?

03

What are the advantages and limits of delegation?

A to-do list with one listener

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

toggled 1
added 3
toggled 3
deleted 2
items left: 2