Quiz Entry - updated: 2026.07.05
How do you create and append new elements to the DOM?
Build a node with document.createElement("tag"), set its content/attributes, then insert it with appendChild() or append().
// Create element
const div = document.createElement("div");
div.className = "card";
div.textContent = "New card";
// Append to parent
document.body.appendChild(div);
// Or use append (more flexible)
// Element
container.append(div);
// Text node
container.append("Text");
// Multiple
container.append(el1, el2);
Insert at specific position:
parent.insertBefore(newElement, referenceElement);
// At start
parent.prepend(newElement);
Remove elements:
// Remove self
element.remove();
// Remove child
parent.removeChild(childElement);
Tip: Build complex elements off-DOM, then append once to minimize reflows.
Go deeper:
document.createElement (MDN) — creating element nodes before inserting them into the tree.