Lesson 4: Creating and Removing Elements

Learning Objectives

By the end of this lesson, learners will be able to:

  • Dynamically create new HTML elements using JavaScript
  • Add those elements to the DOM
  • Set content and apply styles or classes to created elements
  • Remove existing elements from the DOM
  • Understand different approaches to inserting elements (append, prepend, etc.)

Why Create and Remove Elements?

In modern web apps, content often appears dynamically:

  • New messages in a chat
  • Tasks added to a to-do list
  • Cards loaded from an API
  • Items removed when dismissed

JavaScript allows us to build and change the page on the fly, without refreshing.


1. Creating Elements

Step-by-step process:

  1. Create the element:
let newElement = document.createElement("p");
  1. Add content:
newElement.textContent = "This is a new paragraph.";
  1. (Optional) Add styles or classes:
newElement.style.color = "blue";
newElement.classList.add("highlight");
  1. Insert it into the page:
document.body.appendChild(newElement);

appendChild() adds the new element to the end of a parent element (in this case, the <body>).


Example

<div id="container"></div>
let message = document.createElement("div");
message.textContent = "Hello from JavaScript!";
message.classList.add("alert");
document.getElementById("container").appendChild(message);

2. Inserting Elements: append, prepend, appendChild

MethodDescription
appendChild(el)Adds element to the end of parent
append(el)Adds one or more elements or text to end
prepend(el)Adds element to the beginning of parent
container.append(newElement);       // Can add strings too
container.prepend(newElement);      // Inserts at the beginning

3. Removing Elements

There are two main ways to remove elements:


Method 1: element.remove()

Modern and simple (works in most browsers):

let element = document.getElementById("old-item");
element.remove();

Method 2: parent.removeChild(child)

Older method for broader compatibility:

let parent = document.getElementById("list");
let child = parent.firstElementChild;
parent.removeChild(child);

You must access both the parent and child nodes.


Example: Add and Remove List Items

HTML:

<ul id="todo-list"></ul>
<button id="add-btn">Add Task</button>

JavaScript:

let list = document.getElementById("todo-list");
let button = document.getElementById("add-btn");

button.addEventListener("click", function() {
  let task = document.createElement("li");
  task.textContent = "New Task";
  list.appendChild(task);

  // Click the task to remove it
  task.addEventListener("click", function() {
    task.remove();
  });
});

✅ This creates a new list item every time the button is clicked
✅ Clicking a list item removes it from the DOM


Bonus: Replacing Elements

You can also replace one element with another using:

parent.replaceChild(newElement, oldElement);