Attach single event listener to parent container with JavaScript

Because events in JavaScript ""bubble"" up the DOM tree, you can attach a single event listener to the parent container and use event.target to figure out which child was clicked. JavaScript // Attach ONE listener to the parent <ul> document.getElementById('item-list').addEventListener('click', (event) => { // Check if the clicked element was a button if (event.target.tagName === 'BUTTON') { const itemId = event.target.dataset.id; console.log(`Item ${itemId} clicked!`); } }); This uses drastically less memory and automatically handles new items added to the list dynamically—no need to attach new listeners when the DOM updates! #JavaScript #WebPerformance #CodingInterviews #FrontendDev #TechTips"

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories