2025 Update - Delegated Events Implementation for Pure Vanilla JS (no jQuery)
Example - a table #dataTable
exists, but the rows are programmatically added / changed dynamically, the following code snippet will handle clicke events on the dinamically newly added rows:
document.querySelector("#dataTable tbody").addEventListener("click", function(event) {
const row = event.target.closest("tr");
if (row && this.contains(row)) {
console.log(row.textContent.trim());
}
});
That pattern is known as delegated event handling or event delegation.
✅ What is Event Delegation?
Instead of attaching an event listener to each child element (e.g., every <tr>), you attach one listener to a common ancestor (like <tbody>) and then use event.target or event.target.closest() to figure out which child element triggered the event.
Previous Answer (for jQuery):
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.