Creating DOM Elements
Table of Contents + −
In the previous lesson, we learned how to change the look of elements that already exist on the page. Now let’s create brand new elements with JavaScript and add them to the page ourselves.
🏗️ Creating an Element
The document.createElement() method builds a new element. You pass it the tag name as a string, and it hands back an element you can work with.
const item = document.createElement("li");This single line calls createElement("li"), which returns a brand new <li> element and stores it in the item variable. At this point the <li> exists only in memory. It is not on the page yet, so nobody can see it. You still need to give it some content and then attach it to the DOM.
✍️ Setting Content and Attributes
A fresh element is empty. You set its text with textContent, and you set attributes like id, class, or href the same way you would on any element.
const item = document.createElement("li");
item.textContent = "Buy milk";item.id = "first-item";item.className = "todo-item";Let’s walk through what each line does to the element:
- The first line creates the
<li>and holds it initem. item.textContent = "Buy milk"puts the text “Buy milk” inside the element.item.id = "first-item"gives the element anidattribute.item.className = "todo-item"sets itsclassattribute.
The element now has text and attributes, but it still lives only in memory. The next step makes it appear.
A created element does nothing until it is added
Creating an element does not put it on the page. Until you attach it to a parent in the DOM, it stays invisible.
📌 Adding the Element to the Page
To make the element visible, you attach it to a parent element that is already on the page. These are the methods you will use.
| Method | What it does |
parent.appendChild(child) | Adds the child as the last item inside the parent |
parent.append(child) | Also adds at the end, and can accept text and multiple nodes |
parent.prepend(child) | Adds the child as the first item inside the parent |
parent.insertBefore(new, ref) | Adds the new element right before a specific child |
append() is the modern choice for most cases because it accepts plain text and several items at once. appendChild() is the older method and takes only one element.
📄 A Simple Example
This code creates a paragraph, gives it some text, and adds it to the body of the page.
const paragraph = document.createElement("p");
paragraph.textContent = "Hello from JavaScript!";
document.body.append(paragraph);Let’s step through the three lines:
- The first line creates a
<p>element and stores it inparagraph. - The second line sets the paragraph’s text to “Hello from JavaScript!”.
- The third line calls
document.body.append(paragraph)to attach it as the last child of the page body.
When this runs, the new paragraph shows up at the bottom of the page. Without the last line, the paragraph would exist but never appear.
✅ A Practical Example
Building a list one item at a time is a common task. Here we take an array of to-do tasks and add each one to a <ul> already on the page.
const tasks = ["Buy milk", "Walk the dog", "Read a book"];const list = document.querySelector("#todo-list");
for (const task of tasks) { const item = document.createElement("li"); item.textContent = task; list.append(item);}Here is what each part does:
tasksholds the array of strings we want to turn into list items.listselects the<ul>on the page with the idtodo-list.- The
for...ofloop runs once for each task in the array. - Inside the loop, we create an
<li>, set its text to the current task, and append it to the list.
Each loop turn creates a new <li>, sets its text to the current task, and appends it to the list. After the loop, the page shows three list items.
Build first, then attach
Set the text and attributes on an element before you add it to the page. The browser draws the element once, with everything already in place.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
| Forgetting to append the element | The element is created but nothing shows on the page | Call append() or appendChild() on a parent |
| Appending to the wrong parent | The element appears in an unexpected place | Select the correct parent before attaching |
| Building HTML as a string | innerHTML += "..." is error-prone and unsafe with user input | Use createElement and set textContent |
The difference between the last two approaches is worth seeing in code.
// ❌ Building HTML from a string with user datalist.innerHTML += "<li>" + userInput + "</li>";
// ✅ Creating an element and setting its text safelyconst item = document.createElement("li");item.textContent = userInput;list.append(item);Let’s compare the two approaches line by line:
- The first line glues
userInputinto an HTML string, so any tags inside it run as real markup. - The safe version creates an
<li>element instead of writing raw HTML. - It assigns
userInputtotextContent, then appends the element to the list.
Setting textContent treats the input as plain text, so any HTML inside it cannot run as code.
🔧 Try It Yourself!
- Create a
<p>element, set itstextContent, and append it todocument.body. - Add an
idorclassNameto the element before you append it. - Make an array of strings and loop through it, creating one
<li>for each and appending them to a<ul>. - Use
prepend()instead ofappend()and notice that the new item lands at the top.
🧩 What You’ve Learned
- ✅
document.createElement("tag")builds a new element in memory - ✅ Set content with
textContentand attributes likeidorclassName - ✅ A created element does nothing until you add it to the DOM
- ✅
append()andappendChild()add to the end;prepend()adds to the start;insertBefore()adds before a specific child - ✅ Creating elements is safer than building HTML strings
🚀 What’s Next?
Now that you can add elements to the page, we will learn how to take them away. Let’s continue to Removing Elements.