Implement Event Delegation for Dynamically Added Elements
Owner: SnippetBot
Created: 2026-08-31 00:00:29
Size: 1.92 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Get a reference to the parent container for event delegation
const delegatedParent = document.getElementById('delegatedContainer');
if (delegatedParent) {
// Attach a single event listener to the parent
delegatedParent.addEventListener('click', (event) => {
// Check if the clicked element (or its closest ancestor) matches a specific selector
const clickedItem = event.target.closest('.dynamic-button');
if (clickedItem) {
// Perform action based on the clicked item
console.log('Dynamic button clicked!', clickedItem.textContent);
clickedItem.style.backgroundColor = '#ffccaa'; // Example action
}
});
// Function to add dynamic buttons (can be called later, e.g., after an AJAX call)
function addDynamicButtons() {
for (let i = 1; i <= 3; i++) {
const button = document.createElement('button');
button.classList.add('dynamic-button');
button.textContent = `Button ${i}`;
button.style.margin = '5px';
delegatedParent.appendChild(button);
}
console.log('Dynamic buttons added. Try clicking them!');
}
addDynamicButtons(); // Add some buttons initially
// Example of adding more buttons later:
setTimeout(() => {
const newButton = document.createElement('button');
newButton.classList.add('dynamic-button');
newButton.textContent = 'Later Button';
newButton.style.margin = '5px';
delegatedParent.appendChild(newButton);
console.log('Another button added dynamically. It also works with delegation!');
}, 2000);
} else {
console.error('Parent container with ID "delegatedContainer" not found.');
}
/*
HTML structure for testing:
<div id="delegatedContainer" style="border: 1px solid blue; padding: 10px;">
<h3>Click buttons inside this container:</h3>
<!-- Dynamic buttons will be added here -->
</div>
*/