JavaScript Dynamic List: Add or Remove Items in JS

JavaScript dynamic list

You use a dynamic list in JavaScript when the number of items changes while the page runs.

This means you can add or remove. You can also update list items. That does not need to reload the page. It helps you build things like

  • Dropdown menus
  • To-do apps
  • Live search results

A dynamic list gives you more control. It also improves the user experience.

Understand the Dynamic List

A dynamic list in JavaScript is a list that updates while the page runs. You can create new items or remove old ones. Or even change. JavaScript handles these updates in real-time.

You use dynamic lists in web apps that need to react to user input.

For example, users can add or delete tasks in a to-do app. You might let users add extra input fields in a form. Menus also change based on what users select.

Here are the prerequisites to build a dynamic list in JavaScript:

  • Basic HTML knowledge
    You need to know how to create elements like (<ul><ol><li><input> <div><button>).
  • Basic CSS
    You should know how to apply styles to elements, hide or show items, and use layout features like Flexbox.
  • JavaScript fundamentals. you must understand:
    • Variables
    • Data types
    • Arrays
    • Objects
    • Loops
    • Conditionals.
  • DOM manipulation
    You need to know how to select elements and create new elements. Also you need to know how to change content and handle events like click or input.
  • Event handling
    You should know how to add and remove event listeners with addEventListener.
  • Functions and scope
    You need to write functions to handle logic and manage variable scope correctly.
  • Debugging with browser tools
    You should know how to use the browser console and developer tools to track errors and test changes.

HTML Structure for a Dynamic List

You need a basic list element. Use either <ul> for an unordered list or <ol> for an ordered list. This gives you a place to show the items.

Add an input field so users can type in new items. Include a button that adds the item to the list when clicked. You can also use another button to clear the list or remove items.

Here is what we have to do:

JavaScript Dynamic List Items

Here is a simple example:

<div class="container">
    <!-- Form to add a new note -->
    <div class="form-section">
      <h2>Add a New Note</h2>
      <form id="noteForm">
        <label>Title:</label>
        <input type="text" id="noteTitle" required>
        <label>Note:</label>
        <textarea id="noteText" rows="5" required></textarea>
        <button type="submit">Add a new item</button>
      </form>
    </div>

    <!-- Section to display added notes -->
    <div class="notes-section">
      <h2><span id="noteCount">0</span> Notes Added</h2>
      <div id="notesContainer"></div>
    </div>
  </div>

This setup gives you the base. You will connect JavaScript to handle user input and update the list in the next part.

Add Items to the List

You need to create elements on the fly and insert them into the DOM. This is where document.createElement() and methods like appendChild() or insertAdjacentHTML() come in.

Let’s use each one in detail:

Use the document.createElement() to Create HTML Elements

The document.createElement() method is used to create a new HTML element using JavaScript. It doesn’t place the element on the page immediately—you still need to append it to the DOM.

For example:

const newDiv = document.createElement('div');  // creates a <div>
newDiv.className = 'note-card';                // adds a class
newDiv.textContent = 'This is a new note';     // sets text

You can also add inner HTML like this:

newDiv.innerHTML = `
  <h3>Note Title</h3>
  <p>Note content goes here.</p>
`;

Append New Elements with appendChild()

You have to use the appendChild() to insert it into the document once you create an element with createElement().

For example:

const notesContainer = document.getElementById('notesContainer');
notesContainer.appendChild(newDiv);  // newDiv is now in the DOM

This adds a new note to the bottom of the container.

Use the insertAdjacentHTML() Function

The insertAdjacentHTML() is a more concise way to add HTML content directly into the DOM. It parses a string of HTML and inserts it into the specified position relative to an element.

notesContainer.insertAdjacentHTML('beforeend', `
  <div class="note-card">
    <h3>Note Title</h3>
    <p>Note content goes here.</p>
  </div>
`);

The 'beforeend' position means the new HTML goes inside the element, at the end (like appendChild()).

Use createElement() when:

  • You need more control.
  • You build complex structures with event listeners.

Use insertAdjacentHTML() when:

  • You insert predefined HTML templates.
  • You need cleaner and faster code.

Remove Items from the List

When users click a “Delete” button, you want to identify which item was clicked and remove it from the DOM. This involves:

  • Detect the clicks with event delegation (especially for dynamic items).
  • Use removeChild() or .remove() to remove the matched element.

Use Event Delegation to Handle Clicks

Event delegation means placing one event listener on a shared parent, not on each item. This is especially useful for elements that are dynamically added to the page.

For example:

document.getElementById('notesContainer').addEventListener('click', function(e) {
  if (e.target.classList.contains('delete')) {
    const noteCard = e.target.closest('.note-card');
    noteCard.remove(); // or use removeChild (see below)
  }
});

e.target is the element that was clicked. closest('.note-card') finds the nearest parent with that class.

Remove Items with .remove() (Simple & Modern)

The .remove() method directly deletes the element from the DOM.

noteCard.remove();

This is a clean one-liner that removes the entire card.

Remove Items with removeChild() (Legacy-Safe)

If you work in an older browser (like IE), or want more control, use removeChild().

const container = document.getElementById('notesContainer');
container.removeChild(noteCard);

You need both the parent node and the child node to use removeChild().

TaskMethodUse When
Detect clicks on dynamic itemsevent delegationBest for dynamic content
Remove an element directly.remove()Simple, modern browsers
Remove with parent referenceremoveChild()Older browser support

Event Listeners for Dynamic Behavior

To make your dynamic list (like a notes app) interactive, you need to use event listeners. These listeners let you respond to actions like button clicks—to add or edit. Or even delete notes.

Handle Button Clicks

You can use addEventListener() to attach functions to buttons when they’re clicked. This is how you capture the user’s actions.

Handle “Add Note” Button

document.getElementById('noteForm').addEventListener('submit', function(e) {
  e.preventDefault();  // Prevent page reload
  // Logic to create and insert a new note
});

You listen for the form submission and run your logic inside that handler.

Delete Button (Already in the DOM)

If the delete button already exists in the page, you can directly attach:

document.querySelector('.delete').addEventListener('click', function() {
  // Remove note
});

Add Listeners to Dynamically Created Elements

When new elements are added to the DOM within JavaScript (like a new note card), their event listeners don’t automatically exist. You must either:

  1. Attach a listener manually right after you create the element.
  2. Use event delegation (preferred for many items).

Attach Directly (not scalable)

const deleteBtn = noteCard.querySelector('.delete');
deleteBtn.addEventListener('click', function () {
  noteCard.remove();
});

Use Event Delegation (scalable & clean)

Attach one listener to the container and detect clicks on buttons using e.target.

notesContainer.addEventListener('click', function(e) {
  if (e.target.classList.contains('delete')) {
    const card = e.target.closest('.note-card');
    card.remove();
  }
});
BenefitExplanation
Works with new elementsNo need to reattach listeners after adding
Better performanceFewer event listeners in memory
Cleaner codeOne place to handle all click logic

Use Arrays to Manage List Data

In a dynamic list app (like a notes app), you store data in an array to keep full control. This approach works well when you add features like edit, save to localStorage, filter, or search.

Store List Items in an Array

You can use an array to store each note as an object with properties like title and text.

For example:

let notes = [];

function addNote(title, text) {
  notes.push({ title, text });
}

Now every time a note is added, you store the data in the array before rendering it.

{ title: "Track Your Daily Progress", text: "Lorem Ipsum..." }

Keep the Array in Sync with the DOM

When you change the array (add/edit/delete), you need to re-render the notes on the page to keep the DOM in sync.

Render Function:

function renderNotes() {
  const notesContainer = document.getElementById('notesContainer');
  notesContainer.innerHTML = ""; // Clear previous notes

  notes.forEach((note, index) => {
    const card = document.createElement('div');
    card.className = 'note-card';

    card.innerHTML = `
      <div class="note-actions">
        <a href="#" class="delete" data-index="${index}">Delete</a>
      </div>
      <h3>${note.title}</h3>
      <p>${note.text}</p>
    `;

    notesContainer.appendChild(card);
  });

  // Update count
  document.getElementById('noteCount').textContent = notes.length;
}

Delete from the Array

To delete a note, remove it from the array with its index, then re-render the list.

notes.splice(index, 1);
renderNotes();

In your delete event handler:

if (e.target.classList.contains('delete')) {
  const index = e.target.getAttribute('data-index');
  notes.splice(index, 1);
  renderNotes();
}
BenefitDescription
Clean data managementSeparate logic from UI
Easy to edit/update/deleteUse splice(), map(), or filter()
Can be saved to localStorageJSON.stringify your array
Useful for future featuresLike:
– Search
– Filters
– Sort
– Pagination

Full Example of JavaScript Dynamic List

Here is the full code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dynamic Notes App</title>
  <style>

    *, *::after, *::before {
        box-sizing: border-box;
    }

    body {
      font-family: sans-serif;
      background-color: #f4faff;
      display: flex;
      justify-content: center;
      padding: 40px;
    }

    .container {
      display: flex;
      gap: 40px;
      width: 100%;
      max-width: 1000px;
    }

    .form-section, .notes-section {
      background-color: white;
      padding: 24px;
      border-radius: 16px;
      flex: 1;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }

    .form-section h2, .notes-section h2 {
      margin-bottom: 20px;
    }

    .form-section input, .form-section textarea {
      width: 100%;
      padding: 10px;
      margin-bottom: 16px;
      border: 1px solid #ccc;
      border-radius: 6px;
      font-size: 16px;
    }

    .form-section button {
      width: 100%;
      padding: 12px;
      font-size: 16px;
      background-color: #111827;
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
    }

    .note-card {
      background-color: #f9f9f9;
      padding: 16px;
      border-radius: 12px;
      margin-bottom: 16px;
      position: relative;
    }

    .note-card h3 {
      margin: 0 0 8px;
    }

    .note-card p {
      margin: 0;
    }

    .note-actions {
      position: absolute;
      top: 16px;
      right: 16px;
    }

    .note-actions a {
      margin-left: 10px;
      font-size: 14px;
      cursor: pointer;
      color: #007bff;
      text-decoration: none;
    }

    .note-actions a.delete {
      color: #e53935;
    }
  </style>
</head>
<body>

  <div class="container">
    <!-- Form to add a new note -->
    <div class="form-section">
      <h2>Add a New Note</h2>
      <form id="noteForm">
        <label>Title:</label>
        <input type="text" id="noteTitle" required>
        <label>Note:</label>
        <textarea id="noteText" rows="5" required></textarea>
        <button type="submit">Add a new item</button>
      </form>
    </div>

    <!-- Section to display added notes -->
    <div class="notes-section">
      <h2><span id="noteCount">0</span> Notes Added</h2>
      <div id="notesContainer"></div>
    </div>
  </div>

  <script>
    const noteForm = document.getElementById('noteForm');
    const notesContainer = document.getElementById('notesContainer');
    const noteCount = document.getElementById('noteCount');

    let count = 0;

    noteForm.addEventListener('submit', function(e) {
      e.preventDefault();

      const title = document.getElementById('noteTitle').value.trim();
      const text = document.getElementById('noteText').value.trim();

      if (title && text) {
        count++;
        noteCount.textContent = count;

        const noteCard = document.createElement('div');
        noteCard.className = 'note-card';

        noteCard.innerHTML = `
          <div class="note-actions"> 
            <a href="#" class="delete">Delete</a>
          </div>
          <h3 class='titlecls'>${title}</h3>
          <p class='notecls'>${text}</p>
        `;

        // Handle delete
        noteCard.querySelector('.delete').addEventListener('click', function () {
          notesContainer.removeChild(noteCard);
          count--;
          noteCount.textContent = count;
        });
        
        // Append note
        notesContainer.appendChild(noteCard);
        noteForm.reset();
      }
    });
  </script>

</body>
</html>

Wrapping Up

You learned how to build a dynamic list in JavaScript. You saw how to add new items and update the list in real-time. Also how to remove items based on user actions.

You also worked with the DOM, used arrays to manage your data, and handled events with event delegation.

Here is a quick recap of what you did:

  • Created HTML structure with form inputs and a container for notes
  • Used document.createElement() and insertAdjacentHTML() to add items
  • Attached event listeners to handle add and delete actions
  • Used .remove() and removeChild() to delete items from the DOM
  • Managed list data in a JavaScript array
  • Synced the array and DOM with a renderNotes() function
  • Handled user input and events in a clean, scalable way
Previous Article

Code Structure: How to Structure JavaScript Code

Next Article

How to Install PHP on a Raspberry Pi

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.