A dynamic list updates based on user actions like adding, removing, or editing items. In this tutorial, you'll learn how to create a dynamic list using HTML, CSS, and JavaScript.
Prerequisites
- Basic knowledge of HTML, CSS, and JavaScript
- A code editor (like VS Code)
- A browser for testing
Set Up HTML Structure
Create a basic HTML file:
<!DOCTYPE html> <html> <head> <title>Dynamic List</title> <style> ul { padding-left: 20px; } li { margin-bottom: 5px; } button { margin-left: 10px; } </style> </head> <body> <h2>Dynamic List</h2> <input type="text" id="itemInput" placeholder="Enter item"> <button onclick="addItem()">Add</button> <ul id="itemList"></ul> <script src="script.js"></script> </body> </html>
Write JavaScript Logic
Create a file named script.js and add the following code:
function addItem() { const input = document.getElementById('itemInput'); const value = input.value.trim(); if (value === '') return; const li = document.createElement('li'); li.textContent = value; const removeBtn = document.createElement('button'); removeBtn.textContent = 'Remove'; removeBtn.onclick = function () { li.remove(); }; li.appendChild(removeBtn); document.getElementById('itemList').appendChild(li); input.value = ''; input.focus(); }
How It Works?
- The user types a value in the input field.
- When the Add button is clicked, addItem() runs.
- It creates a new
- with the input text and a "Remove" button.
- Clicking "Remove" deletes that item.
Here is the full example in JSFiddle.
Conclusion
You now have a simple dynamic list using JavaScript. You can improve it by saving items to localStorage, adding edit buttons, or using frameworks like React for complex UIs.
Top comments (0)