Challenge - DOM app
Build a note cards board with querySelector, createElement and events.
Note cards board
In this challenge you will build a note cards board. First you select the board element with querySelector.
To add a new note you create an article with document.createElement and attach it with appendChild.
For deletion, instead of a listener on each card you use event delegation: the listener stays on the board and event.target.closest('article') finds the clicked card. Cards added later work automatically.
The event delegation pattern
Event delegation manages many children with a single listener. The listener is attached to the board container; no separate listener is set on each card.
When a click arrives you call event.target.closest('.note'). It walks upward from the clicked element and returns the first matching .note card. If the click landed outside a card it returns null.
When not null you remove the card with remove(). This pattern catches cards added later too.
Exercise Write the addNote function
Write the addNote(text) function. Select the board with querySelector('.board'), create a new card with createElement('article'), set its textContent, add the class note, and attach it with appendChild.
Show example solution
Open addNote(text). Inside, select the board with querySelector('.board'), create a card with createElement('article'), set textContent to text, call classList.add('note'), and appendChild it to the board.
Example solution:
function addNote(text) {
const board = document.querySelector('.board');
const card = document.createElement('article');
card.textContent = text;
card.classList.add('note');
board.appendChild(card);
}
Test yourself
-
Where do you attach the listener in event delegation?
- To a single container wrapping all cards
- To each card separately
- Only to the first card
- To document.body
Show answer
To a single container wrapping all cards — Correct. The listener is on the container; closest() finds the clicked child.
-
Create a card and add it to the board
const card = document.____; card.textContent = text; board.appendChild(card);Show answer
const card = document.createElement('article'); card.textContent = text; board.appendChild(card);