Creating & Modifying Elements in JavaScript
DOM mutation primitives: createElement plus appendChild/prepend/insertBefore place nodes, textContent sets safe text (never innerHTML with user data — XSS), classList add/remove/toggle manages classes without string surgery, and setAttribute/dataset handle attributes. remove() detaches; replaceWith swaps.
Batch with DocumentFragment or single innerHTML template builds (static strings only!) to avoid layout thrash — appending in a loop reflows per iteration. Event listeners survive moves but die with removed nodes unless delegated.
Create and place
document.createElement("li") then parent.append(li) — explicit node construction, no parsing.
textContent, not innerHTML, for data
el.textContent = userInput is XSS-safe; innerHTML parses markup — user data through it executes scripts.
classList manages classes
add/remove/toggle/contains — no className string splitting, toggle with force flag for deterministic state.
Batch inserts
DocumentFragment collects nodes for one append, or build one HTML string for a single innerHTML write.
let ul = document.querySelector("#list");let li = document.createElement("li");li.textContent = "new";li.classList.add("fresh");ul.append(li);console.log(ul.lastChild.className);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.