Handling events efficiently on dynamically created or nested elements | Javascript

 // Using event delegation
parentElement.addEventListener('click', event => {
    if (event.target.matches('.specific-element')) {
        // Handle the event for the specific element
    }
});
 

AI Explanation

This code snippet demonstrates how to implement event delegation in JavaScript to handle click events on specific elements efficiently. Event delegation is a technique where a single event listener is added to a parent element, which then delegates the handling of events to its children. Here's an explanation of the given code: 1. The code adds a click event listener to the `parentElement` element. 2. When a click event occurs within the `parentElement`, the callback function is executed. 3. Inside the callback function, it checks if the event target (the element that triggered the event) matches the selector ".specific-element" using the `matches()` method. 4. If the event target matches the specific element with the class "specific-element", the block of code inside the `if` statement is executed to handle the event for that specific element. By using event delegation in this way, you can handle click events on multiple elements efficiently without having to add individual event listeners to each element. This approach is particularly useful when dealing with dynamic content or a large number of elements.