textContent
Write plain text into an element.
JavaScript can change visible content, but the method you choose decides whether the update is safe, readable and maintainable.
status.textContent = "Saved"; list.replaceChildren(firstItem, secondItem); input.value = "Draft";
DOM & HTML Interaction
Use textContent for plain text. It treats the value as text, not markup, which makes it the default choice for user-facing strings.
Use value for form fields, hidden for visibility state and replaceChildren when you want to rebuild child nodes safely.
innerHTML parses HTML. It is powerful, but it becomes dangerous when untrusted text can reach it.
Write plain text into an element.
Parse and insert HTML markup.
Read or write form control values.
Replace child nodes without string-building HTML.
Examples
const item = document.createElement("li");
item.textContent = record.title;
list.append(item);
list.innerHTML += `<li>${record.title}</li>`;
// Dangerous when title contains unexpected markup.
Code patterns
These patterns are the DOM moves you use constantly: select, read, change, create, navigate and render.
Safe default for labels and messages.
message.textContent = "Saved successfully";
Inputs store their visible value in value.
const value = input.value.trim(); input.value = value;
Build nodes and replace the list at once.
const item = document.createElement("li");
item.textContent = "Ready";
list.replaceChildren(item);
Do not put external text directly into innerHTML.
container.innerHTML = "<strong>Ready</strong>";
Rules that matter
DOM APIs are powerful because they affect the live page. Use them with stable hooks, clear state and safe text updates.
It is predictable and safe for text.
textContent does not change an input value.
It is easy to create injection bugs.
It communicates intent better than inline display changes.
createElement keeps data and markup separate.
replaceChildren avoids stale duplicated content.
Production thinking
Most interface bugs are content bugs: the wrong text, unsafe HTML or stale state in the wrong element.
Dynamic messages should be readable as text and, when important, placed in a status region.
Production code should centralize rendering patterns so content updates are safe by default.
Critical text should not depend on fragile client-side string injection.
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);