JAVASCRIPT
Dynamically Add and Remove Items in a JavaScript List
Explore how to programmatically create new list items, append them to a container, and implement functionality to remove individual items from a dynamic list.
function setupDynamicList(listContainerId, inputId, addButtonId) {
const listContainer = document.getElementById(listContainerId);
const itemInput = document.getElementById(inputId);
const addButton = document.getElementById(addButtonId);
if (!listContainer || !itemInput || !addButton) {
console.error('One or more required elements for the dynamic list not found.');
return;
}
const addItem = () => {
const itemText = itemInput.value.trim();
if (itemText === '') {
alert('Please enter an item.');
return;
}
const listItem = document.createElement('li');
listItem.textContent = itemText;
listItem.style.cssText = 'display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid #eee;';
const removeButton = document.createElement('button');
removeButton.textContent = 'Remove';
removeButton.style.cssText = 'background-color: #f44336; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; margin-left: 10px;';
removeButton.addEventListener('click', () => {
listContainer.removeChild(listItem);
});
listItem.appendChild(removeButton);
listContainer.appendChild(listItem);
itemInput.value = ''; // Clear input
itemInput.focus();
};
addButton.addEventListener('click', addItem);
itemInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
addItem();
}
});
}
// Usage example (HTML):
// <input type="text" id="listItemInput" placeholder="Enter new item">
// <button id="addListItemButton">Add Item</button>
// <ul id="myDynamicList"></ul>
//
// setupDynamicList('myDynamicList', 'listItemInput', 'addListItemButton');
How it works: This snippet demonstrates how to create and manage a dynamic list of items using vanilla JavaScript. It allows users to add new items via an input field and a button (or Enter key). Each new item is dynamically created as an `<li>` element, appended to an `<ul>` container, and comes with its own 'Remove' button. Clicking a 'Remove' button efficiently removes that specific item from the list, showcasing dynamic element creation, appending, and removal with event handling.