topskill.dev
CoursesTracks
0
All courses/DOM Manipulation with JavaScriptEvent Target, Current Target, and Delegation
Events and Interaction
3 / 9
← DOM Manipulation with JavaScript
○Open the browser Console safely○Read results, fix a typo, and try again○Change your blank practice page○The page is a tree○follow the document reference○Load a script when the page is ready○initialize a deferred script○Find one element by id or CSS selector○select a notice and label○Compare DOM properties, HTML attributes, and node types○inspect a room input and its nodes○Initialize a page when it is ready✦Module Quiz
○Find every match with querySelectorAll○label every trail stop○Move from a child to its relatives○trace a nested card○Check for missing elements and search within a card○update only the chosen card○Compare a live HTMLCollection with a static NodeList○safely expand a live collection✦Module Quiz
○Safe text and HTML○render a safe notice○Read and change link attributes○update an accessible link○Data attributes and conditional text○announce session availability○Boolean attributes and DOM properties○unlock a volunteer sign-up✦Module Quiz
○Add, remove, and check classes○mark a favourite card○Toggle a panel accessibly○toggle the help panel○Inline styles, classes, and hidden○style and hide a notice○Change a CSS custom property from JavaScript○change a workshop card accent✦Module Quiz
○Create an Element and Append It○Add a Reading List Item○Place Nodes Before and Between○Order the Workshop Agenda○Remove, Replace, and Clear Safely○Refresh a Museum Display○Clone a Card and Insert a Batch○Clone Two Exhibit Cards✦Module Quiz
○Listen for Clicks with a Named Handler○Check Library Hours●Event Target, Current Target, and Delegation○Delegate Pantry Actions○Keyboard Events Without Trapping Keys○Search the Recipe Box○Once, Remove, and Bubble○Control Workshop Notifications✦Module Quiz
○Read a field while someone types○Build a live name preview○Handle submit without leaving the page○Validate a library request○Keep a selection in sync on change and reset○Sync a preference and its reset state○Read multiple checked values with FormData○Build a checkbox-based garden request○Read a number from a form✦Module Quiz
○Filter a list as someone types○Build a live trail finder○Toggle an accessible disclosure○Build a guide menu disclosure○Create and remove items with one delegated listener○Build a neighborhood task board○Sort a workshop table with accessible buttons○Build an accessible sortable resource table✦Module Quiz
○Read selectable cards and detail updates○Build directory cards and a selected profile○Trace live search and an empty state○Add live search to the community directory○Trace safe additions and delegated removal○Add and remove community directory cards✦Module Quiz
○Read and update a live itinerary○Build the workshop itinerary○Add a validated item through a form○Add a workshop session○Filter and remove live entries○Finish the workshop planner✦Module Quiz
○Fetch JSON and render safe text○load recipe cards○Handle loading, empty, and failed responses○handle alert states○Build a query with URLSearchParams○search the catalog○Abort outdated requests○keep the latest result✦Module Quiz
○Load a dashboard from an offline API fixture○Build an events dashboard○Query a dashboard with URLSearchParams○Add event search to the dashboard○Retry requests without stale results○Finish a resilient event dashboard✦Module Quiz

Event Target, Current Target, and Delegation

Handle a list's buttons from its parent

A message board can add rows after the page loads. One listener on the stable list can handle Remove buttons in both old and new rows. This is called event delegation.

The browser passes an event object to each listener. Naming the callback parameter event gives this function a local name for that argument; it is not a selector or an automatically shared variable. Read it during the callback, when currentTarget identifies the running listener.

A click normally bubbles: after the target's listeners, the browser visits listeners on its ancestors. Inside the list listener, event.target is the clicked element and event.currentTarget is the list running that listener. Clicking the nested label makes the span the target, not the button.

element.closest(selector) checks the element itself and then walks upward until it finds a match, or returns null. list.contains(node) checks whether a node belongs inside the list. Together they let the handler ignore plain text and buttons outside its own list.

javascript
list.addEventListener("click", event => {
  const button =
    event.target.closest("button[data-remove]");
  if (!button || !event.currentTarget.contains(button))
    return;
  button.closest("li").remove();
});

The supplied Add message handler builds a row. document.createTextNode("Fresh message ") makes a plain text node to put before its button; assigning button.type sets the button type. button.dataset.remove = "" adds the data-remove marker used by the selector.

Try the preview

Run, add a message, and remove the new row. Remove also works when you click the original nested label. Clicking ordinary row text should leave the row alone. No new Remove listener is needed when a row is added.

Files
  • ⋄index.html
  • ⋄script.js
  • ⋄style.css
Loading editor…