Interactive lists, tables, and menus often create child controls after the first page load. Event delegation keeps one listener on a stable parent element so those later child controls can still run the same JavaScript behavior.

Click events bubble from the innermost clicked element toward its ancestors, so a parent listener can inspect event.target and decide whether the click came from a matching child control. Element.closest() is useful when the user clicks text or an icon inside a button, because it walks back up to the button that carries the action attribute.

The parent must remain in the document while its children change. Replacing the parent also removes its listener, and a child handler that calls stopPropagation() can prevent clicks from reaching it.

Steps to delegate JavaScript events for dynamic elements:

  1. Create index.html in your text editor with the queue markup and file references.
    index.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Support queue</title>
      <link rel="stylesheet" href="styles.css">
      <script src="tickets.js" defer></script>
    </head>
    <body>
      <h1>Support queue</h1>
      <button id="add-ticket" type="button">Add priority ticket</button>
     
      <ul id="ticket-list" aria-label="Support tickets">
        <li class="ticket" data-ticket-id="billing-update">
          <p>Billing update</p>
          <button data-action="complete" type="button">
            <span>Complete ticket</span>
          </button>
        </li>
      </ul>
     
      <p id="ticket-status" role="status">No tickets completed yet.</p>
    </body>
    </html>

    The id on the list gives the listener a stable attachment point. The data-action and data-ticket-id attributes identify controls and tickets independently of their styling. The defer attribute runs tickets.js after the browser has parsed the markup.
    Related: Load JavaScript with defer

  2. Create styles.css beside index.html with the default and completed ticket styles.
    styles.css
    body {
      max-width: 34rem;
      margin: 2rem auto;
      padding: 0 1rem;
      font: 1rem/1.5 system-ui, sans-serif;
      color: #182235;
    }
     
    button {
      padding: 0.6rem 1rem;
      font: inherit;
      cursor: pointer;
    }
     
    #ticket-list {
      padding: 0;
      list-style: none;
    }
     
    .ticket {
      margin: 1rem 0;
      padding: 1rem;
      border: 1px solid #c5cedb;
      background: #f8fafc;
    }
     
    .ticket p { margin: 0 0 0.75rem; }
    .ticket--complete { border-color: #16833a; background: #eefaf1; }
  3. Create tickets.js beside index.html with the queue's element references.
    tickets.js
    const ticketList = document.querySelector("#ticket-list");
    const addTicketButton = document.querySelector("#add-ticket");
    const status = document.querySelector("#ticket-status");
  4. Append the delegated click handler at the end of tickets.js.
    tickets.js
    ticketList.addEventListener("click", (event) => {
      const completeButton = event.target instanceof Element
        ? event.target.closest("button[data-action='complete']")
        : null;
     
      if (!completeButton || !ticketList.contains(completeButton)) {
        return;
      }
     
      const ticket = completeButton.closest("[data-ticket-id]");
      ticket.classList.add("ticket--complete");
      completeButton.disabled = true;
      completeButton.textContent = "Completed";
      status.textContent = `${ticket.dataset.ticketId} completed.`;
    });

    event.target can be the nested span rather than the button. closest() finds the matching button, and contains() rejects a match outside the list. A click on the ticket title finds no matching button and returns without completing anything.
    Related: Add a JavaScript event listener

  5. Append the add-button handler at the end of tickets.js.
    tickets.js
    addTicketButton.addEventListener("click", () => {
      if (ticketList.querySelector("[data-ticket-id='priority-shipping']")) {
        return;
      }
     
      ticketList.insertAdjacentHTML("beforeend", `
        <li class="ticket" data-ticket-id="priority-shipping">
          <p>Priority shipping</p>
          <button data-action="complete" type="button">
            <span>Complete ticket</span>
          </button>
        </li>
      `);
     
      status.textContent = "priority-shipping added.";
    });

    The new ticket is inserted after the list listener already exists, with no listener added to the new button. The first condition prevents duplicate priority tickets. The HTML string contains only fixed markup; user-supplied text belongs in textContent rather than an HTML string.

  6. Save all three files in the same folder.
  7. Open the saved index.html file in your browser. Saved HTML file address entered in Chromium

    The address begins with file:/// and points to the folder where you saved the files. No web server is required.

  8. Click Add priority ticket. Queue with the Add priority ticket button before insertion
  9. Click Complete ticket inside the new Priority shipping item. New priority ticket with its Complete ticket button
  10. Confirm that Priority shipping turns green with a disabled Completed button and the status priority-shipping completed.. Dynamic priority ticket completed through the parent listener
Share this guide