How do you add and remove DOM elements?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Creating and inserting
const el = document.createElement("li");
el.textContent = "New item";
el.className = "item";
list.append(el); // at the end
list.prepend(el); // at the start
ref.before(el); // as a previous sibling
ref.after(el); // as a next sibling
append accepts several nodes and plain strings at once, which appendChild cannot. Use it unless you need the old method's return value.
Removing and replacing
el.remove(); // no parent reference needed
el.replaceWith(newEl);
list.replaceChildren(); // empty the container
list.replaceChildren(a, b); // swap all children in one call
el.remove() replaces the awkward el.parentNode.removeChild(el).
Modifying
el.textContent = "Safe text";
el.setAttribute("data-id", "7");
el.dataset.id = "7"; // same thing, nicer
el.classList.toggle("active", isActive);
el.style.setProperty("--x", "10px");
Use textContent, not innerHTML
innerHTML parses its input as markup, so any user-supplied string becomes a route to XSS:
el.innerHTML = userInput; // dangerous
el.textContent = userInput; // always safe
If you genuinely need to insert markup, sanitise it first, or build the nodes explicitly. insertAdjacentHTML has the same risk.
Two performance notes
Inserting inside a loop touches the live DOM every iteration. Build in a DocumentFragment and insert once instead. And clearing with innerHTML = "" works but replaceChildren() is clearer and avoids re-parsing.
One correctness point: removing an element does not remove listeners attached to it, but once nothing references the node it is collected along with them. Leaks come from listeners on document or window that outlive the element they were about.
