Learn JavaScript
❯ browser_dom.dom_modify

Creating & Modifying Elements in JavaScript

$concept

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.

$how it works
1

Create and place

document.createElement("li") then parent.append(li) — explicit node construction, no parsing.

2

textContent, not innerHTML, for data

el.textContent = userInput is XSS-safe; innerHTML parses markup — user data through it executes scripts.

3

classList manages classes

add/remove/toggle/contains — no className string splitting, toggle with force flag for deterministic state.

4

Batch inserts

DocumentFragment collects nodes for one append, or build one HTML string for a single innerHTML write.

$example
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);
Output
fresh
1A list item is created detached — invisible until placed.
2Safe text plus a managed class prepare it without markup parsing.
3Appending attaches it; reading back confirms the fresh class landed.
$use cases
Rendering lists by building nodes (or one HTML string) then attaching once
XSS-safe user content exclusively through textContent
Class-driven styling via classList toggles
dataset attributes for element-bound metadata

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.