// 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:

Click buttons inside this container:

*/