WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

JavaScript Β· Intermediate Β· question 25 of 100

How does event delegation work in JavaScript, and why is it important?

πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

Event delegation is a technique in JavaScript where instead of attaching an event listener to each individual element, you attach the event listener to a parent element and then use a conditional statement to check if the event target matches the desired element. If it does, you execute the desired code.

Here’s an example:

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
    <script>
    document.getElementById("list").addEventListener("click", function(event) {
        if (event.target && event.target.nodeName === "LI") {
            console.log("You clicked on: " + event.target.textContent);
        }
    });
    </script>

In this example, an event listener is attached to the ul element with the ID of list. When a click event occurs, the function checks if the event target is an li element. If it is, it logs the text content of the clicked li element to the console.

Event delegation is important because it reduces the number of event listeners attached to the page, which can improve performance and reduce the amount of code needed to handle events. This is especially important for large pages or dynamic content, where attaching an event listener to each individual element can be impractical or slow.

Another benefit of event delegation is that it allows you to handle events for dynamically created elements. If you attach an event listener to a parent element, any child elements that are created dynamically will also trigger the event listener without having to attach a new listener to each element.

In summary, event delegation is a technique in JavaScript where you attach an event listener to a parent element and then use a conditional statement to check if the event target matches the desired element. It is important because it can improve performance, reduce code, and allow for event handling on dynamically created elements.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview β€” then scores it.
πŸ“ž Practice JavaScript β€” free 15 min
πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

All 100 JavaScript questions Β· All topics