Event Delegation for Dynamic Elements
Use event delegation on a parent `<ul>` element to handle clicks on its child `<li>` elements.
document.addEventListener('DOMContentLoaded', function() {
// Attach event listener to parent <ul> element
document.querySelector('#myList').addEventListener('click', function(event) {
// Check if the clicked element is a <li>
if (event.target && event.target.nodeName === 'LI') {
// Handle the click event on the <li> element
console.log('Item clicked:', event.target.textContent);
}
});
});
This code sets up an event listener on the parent <ul> with an id of 'myList'. When a click event occurs, it checks if the target of the click is an <li> element and, if so, logs the text of that <li> to the console. This is the principle of event delegation, which allows us to handle events on dynamically added child elements without having to attach event listeners directly to them.