By the end of this lesson, learners will be able to:
In modern web apps, content often appears dynamically:
JavaScript allows us to build and change the page on the fly, without refreshing.
let newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
newElement.style.color = "blue";
newElement.classList.add("highlight");
document.body.appendChild(newElement);
appendChild() adds the new element to the end of a parent element (in this case, the <body>).
<div id="container"></div>
let message = document.createElement("div");
message.textContent = "Hello from JavaScript!";
message.classList.add("alert");
document.getElementById("container").appendChild(message);
append, prepend, appendChild| Method | Description |
|---|---|
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
There are two main ways to remove elements:
element.remove()Modern and simple (works in most browsers):
let element = document.getElementById("old-item");
element.remove();
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.
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
You can also replace one element with another using:
parent.replaceChild(newElement, oldElement);