So far we've changed elements that already existed. But you can also create brand-new elements from scratch and add them to the page. This is a three-step process:
- Create the element with
document.createElement("tagName"). - Fill it in: set its text, classes and attributes.
- Add it to the page by attaching it to an element that's already there.
// 1. Create
const newItem = document.createElement("li");
// 2. Fill it in
newItem.textContent = "Soup";
newItem.classList.add("highlight");
// 3. Add it to the page
const list = document.querySelector("#food-list");
list.append(newItem);
Refresh, and "Soup" appears at the bottom of the food list, with a yellow highlight. Until step 3, the element only exists in JavaScript's memory, floating in space. Attaching it to the page is what makes it appear.
There are a few ways to attach elements:
| Method | Where the new element goes |
|---|---|
parent.append(child) | Inside parent, at the end |
parent.prepend(child) | Inside parent, at the start |
element.before(newEl) | Just before element, as a sibling |
element.after(newEl) | Just after element, as a sibling |
And to remove an element, just call .remove() on it:
const favorite = document.querySelector(".favorite");
favorite.remove(); // Pancakes has left the building
Building a list from data
Here's where Middle School pays off. Real web pages are usually built from data: an array of objects that came from somewhere (often the internet). Let's turn an array into list items on the page:
const groceries = ["tomatoes", "onions", "rice", "palm oil"];
const list = document.querySelector("#food-list");
list.innerHTML = ""; // clear out the old items first
groceries.forEach((item) => {
const li = document.createElement("li");
li.textContent = item;
list.append(li);
});
The page now shows our grocery list instead of the original foods. If the array had 1,000 items, this exact same code would create 1,000 list items. That's the power of combining loops and the DOM!