Add and Remove List Items with JavaScript (CodePen)
This article will guide you through adding and removing list items using JavaScript, with a working CodePen example.
HTML Structure
First, let's create a basic HTML structure for our list and buttons:
Add/Remove List Items
We have an empty <ul>
element with the ID my-list
, and two buttons: one for adding items (add-item
) and one for removing items (remove-item
).
JavaScript (script.js)
Now, let's add the JavaScript code to handle adding and removing items:
const list = document.getElementById('my-list');
const addItemButton = document.getElementById('add-item');
const removeItemButton = document.getElementById('remove-item');
let listItems = []; // Array to store list items
addItemButton.addEventListener('click', () => {
const newItem = prompt("Enter new list item:");
if (newItem !== null && newItem.trim() !== "") {
listItems.push(newItem);
renderList();
}
});
removeItemButton.addEventListener('click', () => {
if (listItems.length > 0) {
listItems.pop();
renderList();
}
});
function renderList() {
list.innerHTML = ''; // Clear existing list items
listItems.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = item;
list.appendChild(listItem);
});
}
In this code:
- We select the list, add button, and remove button elements.
- We create an array
listItems
to store the items. - When the "Add Item" button is clicked, we:
- Prompt the user for the new item.
- Add the item to the
listItems
array if it's not empty. - Call the
renderList()
function to update the list.
- When the "Remove Item" button is clicked, we:
- Remove the last item from the
listItems
array if it's not empty. - Call the
renderList()
function to update the list.
- Remove the last item from the
- The
renderList()
function:- Clears the existing list items.
- Loops through the
listItems
array. - Creates a new
<li>
element for each item. - Sets the text content of the list item.
- Appends the list item to the list element.
CodePen Example
You can see this code in action in this CodePen:
[CodePen link goes here]
Conclusion
By combining basic HTML, CSS, and JavaScript, we can create interactive lists where users can add and remove items easily. This example can be extended to include more features like editing items, sorting, and more.