createElement, append & textContent
Create elements from data
Lesson 3 of 20 · 11 min · Module 1: The page is a tree
Most pages build lists from data: products, messages, lessons. Instead of writing HTML by hand, JavaScript creates one element per item, so the page always matches the data.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Create elements with createElement
- Build nested structures with append
- Render a list from data
The idea
document.createElement('li') makes a new element that is not on the page yet. Fill it with textContent and className, nest elements with append, and finally append the finished element to something already on the page. The data in this exercise comes from a <script type="application/json"> block, a common way for servers to pass data to a page.
const item = document.createElement('li');
item.className = 'tag';
item.textContent = 'CSS';
document.querySelector('#tags').append(item);
01Create, fill, attach
A new element exists only in memory until you append it to something on the page. Filling it before attaching is efficient and keeps the page from flickering.
02append takes several items
append accepts elements and strings, as many as you like, in order: item.append(title, ' ', minutes). appendChild is the older method and takes exactly one element.
const p = document.createElement('p');
p.append('Total: ', document.createElement('strong'));
console.log(p.outerHTML);<p>Total: <strong></strong></p>03Data drives the page
Because the list is built from the array, adding a course to the data is enough to show it. The check above replaces the data before your script runs to make sure nothing is hard-coded.
Your turn
<li class="course"> containing an <h3> with the name and a <span class="minutes"> such as 45 min, and append it to #courses. Then show the total in #total as Total: 135 min. Use createElement and textContent, not innerHTML.What the checks look for
- One item per course
- Each item has its name and minutes
- The total is shown
- It works with any data, and names stay plain text
Take this with you
Create elements from data instead of writing HTML by hand.
Go a little further
Sort the courses by minutes before rendering them, and mark courses over 50 minutes with a class.