DEV Community

Patricia Hernandez
Patricia Hernandez

Posted on

Create JavaScript Dynamic List (Step-by-Step Guide)

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>

Enter fullscreen mode Exit fullscreen mode

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();
}

Enter fullscreen mode Exit fullscreen mode

How It Works?

  1. The user types a value in the input field.
  2. When the Add button is clicked, addItem() runs.
  3. It creates a new
  4. with the input text and a "Remove" button.
  5. 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)