This website uses cookies to enhance the user experience

JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 13

What is event delegation in JavaScript?

Answer:

Event delegation is a technique where a single event listener is added to a parent element to manage events for multiple child elements. This approach leverages event bubbling, where an event starts from the target element and bubbles up to the ancestor elements. Event delegation is efficient because it reduces the number of event listeners needed and is particularly useful for managing dynamically added elements.

Here is an example demonstrating event delegation:

// HTML structure
// <ul id='parentList'>
//   <li class='childItem'>Item 1</li>
//   <li class='childItem'>Item 2</li>
//   <li class='childItem'>Item 3</li>
// </ul>

// JavaScript code
let parentList = document.getElementById('parentList');

parentList.addEventListener('click', function(event) {
    if (event.target && event.target.matches('li.childItem')) {
        console.log('Item clicked:', event.target.textContent);
    }
});

In this example, an event listener is added to the parent ul element. When any li element with the class childItem is clicked, the event listener logs the text content of the clicked item. This approach efficiently manages the event handling for multiple child elements.

Recent job openings

South Africa, Claremont, Western Cape

Remote

Full-time

posted 4 days ago

India

Remote

Full-time

JavaScript

JavaScript

TypeScript

TypeScript

+4

posted 4 days ago

India, Noida, UP

Remote

Full-time

Python

Python

JavaScript

JavaScript

+5

posted 4 days ago

India

Remote

Contract

JavaScript

JavaScript

TypeScript

TypeScript

+4

posted 4 days ago

Philippines, Mandaluyong City, Metro Manila

Remote

JavaScript

JavaScript

SQL

SQL

+8

posted 4 days ago