w3resource

JavaScript Event Delegation for Dynamic List items

JavaScript Event Handling: Exercise-11 with Solution

Event Delegation on List Items

Write a JavaScript program to handle click events on dynamically added list items using event delegation.

Solution 1: Using Event Delegation with addEventListener

JavaScript Code:

// Create a parent element
const listContainer = document.createElement('ul');
listContainer.id = 'dynamic-list';
document.body.appendChild(listContainer); // Add the parent element to the DOM

// Function to add a new list item
function addListItem(content) {
  const newItem = document.createElement('li'); // Create a new list item
  newItem.textContent = content; // Set the list item text
  listContainer.appendChild(newItem); // Append it to the parent container
}

// Add multiple list items dynamically
addListItem('Item 1');
addListItem('Item 2');
addListItem('Item 3');

// Event delegation: Add a click event listener to the parent
listContainer.addEventListener('click', (event) => {
  if (event.target.tagName === 'LI') { // Check if the clicked element is a list item
    alert(`You clicked on: ${event.target.textContent}`); // Show an alert with the item text
  }
});

Output:

•	Item 1
•	Item 2
•	Item 3

Explanation:

In the above exercise,

    1. Create Parent Element:

    • A <ul> (unordered list) element is created using document.createElement('ul').
    • The id of the <ul> is set to dynamic-list for identification.
    • The <ul> is appended to the document body, making it visible in the DOM.

    2. Function to Add List Items:

    • The addListItem function takes a string (content) as input.
    • A new <li> (list item) is created using document.createElement('li').
    • The text content of the <li> is set to the provided string.
    • The <li> is appended to the parent <ul> (listContainer).

    3. Add Multiple List Items:

    • The addListItem function is called three times with different inputs ('Item 1', 'Item 2', 'Item 3').
    • Three list items are dynamically added to the <ul>.

    4. Event Delegation:

    • A click event listener is added to the parent <ul> (listContainer).
    • When any child <li> is clicked, the event listener checks if the clicked element (event.target) is a list item using event.target.tagName === 'LI'.

    5. Handle Click Event:

    • If the clicked element is an <li>, an alert is displayed showing the text content of the clicked item.
    • This ensures only list items trigger the action, and newly added items are handled without additional listeners.

    Solution 2: Using onclick Property for Delegation

    JavaScript Code:

    // Create the parent element
    const listContainer = document.createElement('ul');
    listContainer.id = 'dynamic-list';
    document.body.appendChild(listContainer); // Add the parent container to the DOM
    
    // Function to add list items
    function addListItem(content) {
      const listItem = document.createElement('li'); // Create a new list item
      listItem.textContent = content; // Set its content
      listContainer.appendChild(listItem); // Append it to the parent container
    }
    
    // Dynamically add items
    ['Apple', 'Banana', 'Cherry'].forEach((item) => addListItem(item));
    
    // Using the onclick property to handle events
    listContainer.onclick = (event) => {
      if (event.target.tagName === 'LI') { // Verify it's a list item
        console.log(`Clicked item: ${event.target.textContent}`); // Log the clicked item
      }
    };
    
    

    Output:

    •	Apple
    •	Banana
    •	Cherry
    

    Explanation:

      1. Create the Parent Element:

      • A <ul> (unordered list) element is created using document.createElement('ul').
      • The id of the <ul> is set to dynamic-list for identification.
      • The <ul> is appended to the document.body, making it visible in the DOM.

      2. Function to Add List Items:

      • The addListItem function takes a string parameter (content).
      • A new <li> (list item) is created using document.createElement('li').
      • The text content of the <li> is set to the value of the content parameter.
      • The newly created <li> is appended as a child to the parent <ul> (listContainer).

      3. Dynamically Add Items:

      • An array ['Apple', 'Banana', 'Cherry'] is iterated over using forEach.
      • Each array element is passed as the content argument to the addListItem function, dynamically creating three list items.

      4. Using the onclick Property for Events:

      • The onclick property of the parent <ul> is assigned a function to handle click events.
      • When an item within the <ul> is clicked, the event.target property identifies the clicked element.
      • The if condition ensures that only <li> elements trigger the event logic.
      • The console.log statement logs the text content of the clicked <li>0. element to the console.

    Live Demo:

    See the Pen javascript-event-handling-exercise-11 by w3resource (@w3resource) on CodePen.


    Improve this sample solution and post your code through Disqus.

    Event Handling Exercises Previous: JavaScript double click event: Action on element.
    Event Handling Exercises Next: JavaScript: Prevent Form Submission and Log Inputs.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.