JAVASCRIPT

Create and Manage Dynamic List Items with Removal

Generate multiple list items dynamically from an array of data, append them to the DOM, and empower users to remove individual items using event listeners attached to each element.

function createDynamicList(dataArray, containerId) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.warn(`Container element with ID '${containerId}' not found.`);
    return;
  }

  container.innerHTML = ''; // Clear existing content

  dataArray.forEach(item => {
    const listItem = document.createElement('li');
    listItem.className = 'dynamic-list-item'; // Add a class for styling
    listItem.textContent = item.text; // Assume item has a 'text' property

    const removeButton = document.createElement('button');
    removeButton.textContent = 'Remove';
    removeButton.className = 'remove-item-button';
    
    // Attach a click listener for removal directly to each button
    removeButton.addEventListener('click', function() {
      listItem.remove(); // Removes the listItem element from the DOM
      console.log(`Item '${item.text}' removed.`);
    });

    listItem.appendChild(removeButton);
    container.appendChild(listItem);
  });
  console.log('Dynamic list created.');
}

// Example Usage:
// HTML: <ul id="myDynamicList"></ul>
const myData = [
  { id: 1, text: 'First item' },
  { id: 2, text: 'Second item' },
  { id: 3, text: 'Third item' }
];

createDynamicList(myData, 'myDynamicList');
How it works: This snippet demonstrates how to dynamically generate a list of items from a JavaScript array and append them to a specified container in the DOM. For each item, it creates a list element (`<li>`) and a 'Remove' button. Crucially, a click event listener is attached to each 'Remove' button, enabling users to delete individual list items directly from the UI using `element.remove()`. This pattern is useful for managing user-generated content or interactive lists.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs