4. Architecture, Testing & Tooling
Event Delegation, State-Driven Rendering & XSS-Safe DOM Updates
Architect maintainable browser UIs without framework magic: attach one delegated listener for dynamic lists, separate state from render(), and block XSS using textContent.
- Use event bubbling and e.target.closest() to handle clicks across dynamic lists with one listener
- Separate pure state transitions from DOM rendering (state -> render())
- Prevent Cross-Site Scripting (XSS) by using textContent and createElement instead of raw innerHTML
In beginner DOM tutorials, people attach button.addEventListener("click", ...) inside a loop for every single item—and the moment a new item is added, its buttons don't work, or calling innerHTML = userInput opens a dangerous XSS security vulnerability!
Professional frontend codebases (including React under the hood!) rely on three clean DOM patterns: Event Delegation, State → Render separation, and XSS-safe DOM creation.
1. Event Delegation with e.target.closest(...)
<ul id="list"> ← Single click listener attached here!
Clicking a child button bubbles up to <ul id='list'>; e.target.closest('[data-id]') identifies which item was clicked—even for newly added items!
Events in the DOM bubble upward from the clicked child <button> up through <li> → <ul> → <body>. Instead of attaching 500 listeners to 500 <li> buttons, attach one listener to the stable parent <ul>:
listEl.addEventListener("click", (event) => {
const btn = event.target.closest("button[data-action]");
if (!btn) return; // Clicked empty space, not an action button
const row = btn.closest("li[data-id]");
if (!row) return;
const id = row.dataset.id;
const action = btn.dataset.action; // "toggle" or "delete"
handleAction(action, id);
});Why event.target.closest("button[data-action]") instead of event.target.matches(...)? Because if the button contains an <svg> icon or <span>, event.target might be the inner icon—.closest() walks up to the <button> reliably!
2. State-Driven UI (state -> render()) & XSS Safety
Never store application truth inside DOM text (el.textContent) and try to scrape it back later. Keep a single plain JavaScript state array/object, update it cleanly, and call render():
Writing li.innerHTML = "<span>" + userTitle + "</span>" lets a malicious user enter <img src=x onerror="alert('XSS')"> and execute arbitrary JavaScript in other users' browsers! Always build elements with document.createElement(...) and set user text via el.textContent = userTitle, which automatically escapes HTML characters.
Try It Yourself in the Playground
Build and interact with a state-driven, delegated, XSS-safe Task List right in the browser (try typing <script>alert(1)</script> as a task title to verify textContent escapes it harmlessly!):
Mini-Challenge: Why does listEl.addEventListener("click", ...) keep working automatically when new <li> rows are added later, whereas attaching listeners directly to each <li> button breaks?
Quick Checkpoints
Why should you use event.target.closest('button[data-action]') instead of event.target.matches('button[data-action]') in event delegation?
What is the safest way to display untrusted user-submitted text inside a DOM element?