What is Event Delegation and how does it work?
Event delegation is a technique where a single event listener is added to a parent element instead of each child element individually. It takes advantage of event bubbling in the DOM.
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
// Get the parent element
const list = document.getElementById('myList');
// Attach a single click listener to the parent
list.addEventListener('click', function(event) {
// Check if a list item (li) was clicked
if (event.target && event.target.nodeName === 'LI') {
alert('You clicked: ' + event.target.textContent);
}
});
No comments:
Post a Comment