The browser
textContent and innerHTML
The safe way to read or change an element's text — unlike innerHTML, which turns the string into markup.
Why it exists
You change text on a page all the time: the cart counter, a user's name, an error message. The "shortest" way — innerHTML — is dangerous: if the string contains markup from someone else, it becomes part of your page, handlers like onerror included (that's XSS). textContent does the job of "show this text" and nothing more — it never calls the HTML parser at all, so it can't do harm.
Where it's used
- Show what a person typed: a name, a comment, a task title, a chat message.
- Update a number or a status: "Cart: 3", "Saved", "Network error".
- Read an element's text: in UI tests, when searching a list.
innerHTML— for your own, pre-written markup with no variables inside, like an empty-state template.
Syntax
el.textContent // all the text of the element and its descendants
el.textContent = "Latte" // replace the content with text
el.innerHTML = "<b>Hit</b>" // replace the content with markupExamples
function showComment(box, comment) {
box.textContent = comment;
}
// showComment(box, "<b>Tasty!</b>") shows the characters
// <b>Tasty!</b> on screen, not bold textfunction escapeHtml(text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
escapeHtml("<b>Hit</b>"); // → "<b>Hit</b>"
escapeHtml("Tom & Jerry"); // → "Tom & Jerry"& goes first, or it would break the characters already replaced.function renderComment(list, comment) {
const li = document.createElement("li");
li.textContent = `${comment.author}: ${comment.text}`;
list.append(li);
}
// Even if comment.text is '<img src=x onerror="…">',
// the page shows nothing but textcreateElement + textContent.function showEmptyState(list) {
list.innerHTML = "<li class=\"empty\">Nothing here yet. <b>Add your first task!</b></li>";
}
// The whole string is ours, with no variables inside — innerHTML is fine hereinnerHTML is fine: constant markup you wrote yourself.Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Reading textContent glues the text of all the element's descendants into one string — no tags, with the spaces and line breaks from the HTML.
Writing textContent = string removes all of the element's children and inserts a single text node. The <, > and & characters in it are just characters.
innerHTML = string also removes the children, but then runs the HTML parser: the string is read as if it were a piece of an HTML file, and everything that looks like a tag becomes an element with attributes. Scripts in <script> are deliberately not run, but handler attributes (onerror, onload) do fire — and that's what XSS is built on.
The defense when building HTML is escaping: replace & with &, < with < and so on. Frameworks do it by default: in React, {comment} is always text, and raw HTML goes in only through the scary-sounding dangerouslySetInnerHTML.
There's also innerText: similar to textContent, but it takes CSS into account (it won't return hidden text) and forces the browser to recalculate layout — it's slower.
Traps
When to pick something else
When you need to insert markup rather than text, textContent won't help — build elements with createElement. Keep innerHTML for constant pieces of markup you wrote yourself, with not a single variable inside. And if HTML comes from people and really has to be shown (say, an article from a rich-text editor), it goes through a dedicated sanitizer such as DOMPurify.
Practice
Lessons where this appears
- A website for the Purrfect CaféTale · Chapter 18 · DOM: the page as a tree
- Why is innerHTML dangerous?Why? · Chapter 18 · DOM: the page as a tree
- Cats looking for a homeLab · Chapter 18 · DOM: the page as a tree
- The Crooked SelectorBoss · Chapter 18 · DOM: the page as a tree
- Filtering to-dosLab · Chapter 23 · Project: a to-do app
- The Living PageBoss · Chapter 23 · Project: a to-do app