createElement
Create a new element object.
Creating and removing elements lets JavaScript render interfaces from data without writing fragile HTML strings.
const item = document.createElement("li");
item.textContent = "Created safely";
list.append(item);
DOM & HTML Interaction
document.createElement creates a real element object. You can set text, attributes, classes and event listeners before inserting it.
append, prepend, before, after and remove let you place or remove nodes clearly.
When rendering many items, build them first and then insert them together. This keeps code readable and can reduce layout work.
Create a new element object.
Insert nodes at the end or beginning.
Remove a node from the document.
Collect nodes before inserting them.
Examples
function renderItem(record) {
const item = document.createElement("li");
item.textContent = record.title;
return item;
}
list.innerHTML += `<li>${record.title}</li>`;
Code patterns
These patterns are the DOM moves you use constantly: select, read, change, create, navigate and render.
Safe pattern for dynamic labels.
const item = document.createElement("li");
item.textContent = record.title;
Add the element to the document.
list.append(item);
Elements can remove themselves.
item.remove();
Insert many nodes at once.
const fragment = document.createDocumentFragment(); records.forEach(record => fragment.append(renderItem(record))); list.replaceChildren(fragment);
Rules that matter
DOM APIs are powerful because they affect the live page. Use them with stable hooks, clear state and safe text updates.
Configure nodes before they enter the document.
Avoid parsing user-controlled data as HTML.
It clears stale nodes in one clear operation.
element.remove is readable and direct.
They help organize multi-node rendering.
A function that returns one element is easy to reuse.
Production thinking
Safe rendering patterns are the difference between a maintainable UI and a pile of string concatenation.
Created elements still need real semantics: use buttons for actions, lists for lists and labels for inputs.
Production rendering code should be deterministic: the same data should produce the same DOM.
Dynamic lists should not replace important static content unless client rendering is reliable.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain the DOM operation and its failure path, you are ready to use it in real UI code.
Senior audit upgrade
Prefer textContent, createElement, templates and replaceChildren for normal UI rendering. Reach for innerHTML only when the markup is controlled and the risk is understood.
const item = document.createElement("li");
item.textContent = userInput;
list.replaceChildren(item);