Creating and Removing Elements
Build new DOM nodes from data and attach them to the page — how lists, cards, and entire views are rendered.
Editing existing elements is half the story. The other half is creating them — that is how a feed, a search results list, or a cart comes to exist at all.
The recipe: create → fill → attach
const li = document.createElement("li"); // 1. create (not on the page yet)
li.textContent = "Learn the DOM"; // 2. fill it
list.appendChild(li); // 3. attach to a parent
A new element floats unattached until you append it — appendChild is the
moment it appears.
Building structured content
Elements nest the same way they do in HTML:
const card = document.createElement("article");
card.className = "card"; // className sets the class attribute
const h3 = document.createElement("h3");
h3.textContent = "Ada Lovelace";
const p = document.createElement("p");
p.textContent = "Wrote the first algorithm.";
card.appendChild(h3);
card.appendChild(p);
feed.appendChild(card);
Rendering from data — the pattern that runs the web
const skills = ["HTML", "CSS", "JavaScript"];
const list = document.querySelector("#skills");
for (const skill of skills) {
const li = document.createElement("li");
li.textContent = skill;
list.appendChild(li);
}
The data lives in the array; the DOM is just its projection. Change the array, re-render, and the page follows. Every framework you will ever learn is a shortcut around this loop.
for...of — looping without an index
for (const item of items) visits each value in turn — perfect when you do
not need the index.
Removing
item.remove(); // the element removes itself
Accessibility note
Screen readers follow the DOM, so structure matters even when JavaScript builds it: use real list elements for lists, headings in order, and the same semantic elements you would have written by hand.
What you learned
createElement→ fill →appendChildclassNamesets classes on new elements- Render-from-data: loop the array, build one element per item
for...ofvisits values without an index;.remove()deletes
Next: making the page respond to people — events.