Hello! Welcome back to our course on building dynamic web applications.
In the last two lessons, you learned how to select any element on the page and then modify its content, styles, and attributes. That's a powerful skill set, but it's limited to the HTML that's already on the page when it loads. Today, we're going to break that limitation.
This lesson focuses on the learning outcome: Create, append, and remove DOM elements to build interactive interfaces. You'll learn how to dynamically generate new HTML elements entirely with JavaScript and add them to, or remove them from, your web page. This is the foundation for creating features like to-do lists, comment sections, photo galleries, and displaying data fetched from an APIβall core tasks for a web developer.
Our process will follow a simple, repeatable pattern:
- Create a new element in JavaScript's memory.
- Modify its content and appearance.
- Append it to the live DOM for the user to see.
Let's start building!
1. The Create-Modify-Append Workflow
Creating and adding new elements to the page almost always follows these three steps. Think of it like building with LEGOs: you pick a new brick (create), maybe stick a decal on it (modify), and then snap it onto your creation (append).
Step 1: Creating an Element
To create a new element, we use the document.createElement() method. You pass it a string with the tag name of the element you want to create.
// Creates a <div> element, but it only exists in our script's memory for now.
const newDiv = document.createElement('div');
// Creates a paragraph element.
const newParagraph = document.createElement('p');
// Creates an image element.
const newImage = document.createElement('img');
Crucially, this does not add the element to the page. The element exists only as a JavaScript object in a variable. This is intentional, as it allows us to perform Step 2.
Step 2: Modifying the Element
Once the element is created, you can use all the techniques from our last lesson to modify it before it becomes visible. You can add text, classes, attributes, and styles.
// Continuing from above...
const newDiv = document.createElement('div');
// Modify its content
newDiv.textContent = "I am a brand new div!";
// Modify its style by adding a class (assuming .new-div is in your CSS)
newDiv.classList.add('new-div');
// Modify its attributes
newDiv.setAttribute('id', 'my-first-dynamic-element');
Step 3: Appending the Element to the DOM
After your element is configured, it's time to add it to the page. To do this, you first need to select a parent element (where you want to place your new element) and then use a method to append your new element as a child.
The most common and modern method is .append().
To see this workflow in action, let's watch a short video.
Learn DOM Manipulation In 18 Minutes
The video 'Learn DOM Manipulation In 18 Minutes' by Web Dev Simplified clearly demonstrates how to create an element and add it to the page. It also explains the difference between the modern .append() and the older .appendChild().
Watch from 01:04 to 05:25. Focus on: The two-step process: document.createElement() first, then body.append(). How to add content to the new element using .innerText or .textContent before appending. The key advantages of .append() (it can handle strings and multiple elements) over .appendChild().
As the video highlights, while .appendChild() works, .append() is generally preferred because it's more flexible. For this course, we'll primarily use .append().
2. More Ways to Add Elements
Appending adds an element as the last child of its parent. But you can also add elements at the beginning, or even next to other elements (as siblings).
Here's a quick summary of the most useful methods:
| Method | Description |
|---|---|
parent.append(child) |
Adds child as the last child of parent. |
parent.prepend(child) |
Adds child as the first child of parent. |
element.before(newEl) |
Adds newEl as a sibling before element. |
element.after(newEl) |
Adds newEl as a sibling after element. |
For a more visual explanation of these methods, the following resource is very helpful.
The Odin Project's lesson on DOM Manipulation provides excellent text-based explanations and code examples for these methods.
Read the sections titled 'Element creation' and 'Append elements'. This will reinforce what you saw in the video and also introduce the insertBefore() method, which is an older alternative to .before().
3. Removing Elements from the DOM
Removing elements is much simpler. If you have a reference to an element, you can remove it directly using the .remove() method.
Let's return to our video guide for a quick demonstration.
Learn DOM Manipulation In 18 Minutes
This short clip from the same video shows how simple it is to remove elements.
Watch from 10:12 to 11:37. Notice the modern .remove() method called directly on the element you want to delete. The video also mentions .removeChild(), an older method that requires you to reference the parent element first.
Just like with append, the modern element.remove() is the easiest and most common way to delete an element. You'll use this frequently to remove items from a list or hide components from the UI.
Test your understanding!
Given the following HTML:
<div id="container">
<p id="p1">First paragraph.</p>
</div>
Write the JavaScript code to create a new paragraph with the text "Second paragraph.", give it an ID of p2, and insert it after the first paragraph. Then, write a line to remove the first paragraph.
Show answer
// Select the existing paragraph
const p1 = document.querySelector('#p1');
// 1. Create the new element
const p2 = document.createElement('p');
// 2. Modify it
p2.textContent = 'Second paragraph.';
p2.id = 'p2';
// 3. Append it (in this case, add it *after* p1)
p1.after(p2);
// Now, remove the first paragraph
p1.remove();
After this code runs, the HTML inside <div id="container"> will be <p id="p2">Second paragraph.</p>.
4. Practice Exercise
Let's apply these concepts with a hands-on exercise from The Odin Project. This will test your ability to create, modify, and append multiple elements.
Your Task:
- Create a new folder on your computer. Inside it, create
index.htmlandscript.js. - Set up your
index.htmlfile with a basic structure, including a<body>with a single<div id="container"></div>inside it, and link yourscript.jsfile. - In your
script.jsfile, write the code to achieve the following:- Create a
<p>element with red text that says βHey Iβm red!β and add it to the containerdiv. - Create an
<h3>element with blue text that says βIβm a blue h3!β and add it to the containerdiv. - Create a
<div>with a black border and a pink background. Inside thisdiv, add another<h1>that says βIβm in a divβ and a<p>that says βME TOO!β. Finally, add thisdiv(with its children) to the main containerdiv.
- Create a
This exercise is adapted from the "DOM Manipulation and Events" resource (ID: LINK, section 6).
Show Solution
Your script.js should look something like this:
// Select the main container
const container = document.querySelector('#container');
// Create and append the red paragraph
const redP = document.createElement('p');
redP.style.color = 'red';
redP.textContent = "Hey Iβm red!";
container.append(redP);
// Create and append the blue h3
const blueH3 = document.createElement('h3');
blueH3.style.color = 'blue';
blueH3.textContent = "Iβm a blue h3!";
container.append(blueH3);
// Create the container div with border and background
const contentDiv = document.createElement('div');
contentDiv.style.border = '1px solid black';
contentDiv.style.backgroundColor = 'pink';
// Create the h1 and p for inside the div
const innerH1 = document.createElement('h1');
innerH1.textContent = "Iβm in a div";
const innerP = document.createElement('p');
innerP.textContent = "ME TOO!";
// Append the h1 and p to the new div
contentDiv.append(innerH1, innerP); // .append() can take multiple elements!
// Append the new div to the main container
container.append(contentDiv);
Conclusion
Fantastic work! You now have the complete set of fundamental skills for manipulating the DOM: selecting, modifying, creating, appending, and removing. This is the bedrock of interactive frontend development.
Key Takeaways:
- Create-Modify-Append: Always follow this pattern. Create with
document.createElement(), modify with properties liketextContentandclassList, and then add to the page withappend()orprepend(). - Memory vs. DOM:
createElement()makes an element that only JavaScript knows about. It only becomes visible to the user after you append it to an element that is already in the DOM. - Modern Methods: Prefer modern, simple methods like
.append()and.remove()over their older, more complex counterparts like.appendChild()and.removeChild().
As a final takeaway, here is a helpful cheat sheet that summarizes many of the methods we've discussed. It can be a great reference as you practice.
In our next lesson, "Handle user events such as clicks, input changes, and form submissions," we will finally make our pages truly interactive. You'll learn how to listen for user actions and run your DOM manipulation code in response. This will connect all the dots and allow you to build applications that feel alive.