JavaScript dynamically builds UI components by creating elements with document.createElement() and placing them into the page with modern methods like append(), prepend(), before(), after(), and remove().
Modern browsers support clean node methods that replace older verbose parent.insertBefore() and parent.removeChild() calls:
parent.append(...nodesOrStrings): Inserts one or more elements (or plain escaped strings) at the end of parent.parent.prepend(...): Inserts elements or strings at the very start of parent.target.before(...) / target.after(...): Inserts sibling elements immediately before or after target.oldEl.replaceWith(newEl): Swaps oldEl with newEl without needing a reference to parentNode.el.remove(): Deletes the element directly from the DOM.DocumentFragmentWhen rendering lists of 50 or 500 items, collect them inside a document.createDocumentFragment() in memory first, then call list.append(fragment) once to minimize page layout work.
const app = document.getElementById("app");
if (app) {
const list = document.createElement("ul");
const fragment = document.createDocumentFragment();
for (const label of ["Variables", "Functions", "Promises"]) {
const li = document.createElement("li");
li.textContent = label;
fragment.append(li);
}
list.append(fragment);
app.append(list);
// Remove the first item directly with .remove()
list.firstElementChild?.remove();
console.log("Remaining items:", [...list.children].map((el) => el.textContent));
}
parent.append(existingNode) moves the node out of its old position! Call existingNode.cloneNode(true) when you need a duplicate.el.append("<b>Hi</b>"): Unlike innerHTML, append() escapes strings as plain text—which is great for safety, yet surprises beginners expecting bold HTML.appendChild() inside a loop on a live table: Attach rows to a DocumentFragment first and append once at the end.append() and appendChild()?append() accepts multiple nodes as well as plain strings and returns undefined. Older appendChild() accepts only one Node object, rejects strings, and returns the appended child.
cloneNode(true) also copy attached addEventListener callbacks?No, cloneNode(true) copies the element, attributes, and child elements, not JavaScript event listeners attached with addEventListener(). Use event delegation on a parent container instead.
el.remove() safe if the element is not attached yet?Yes, calling el.remove() on a detached node safely does nothing and throws no error.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.