How to Change Text Content Using JavaScript DOM
Learn how to change text content in the DOM using JavaScript. Master textContent, innerText, and innerHTML with practical examples for dynamic web pages.
Updating text on a web page is one of the most common tasks in JavaScript. Whether you are building a live counter, displaying search results, or showing validation messages, you need to know how to read and change text content through the DOM. JavaScript provides three main properties for this: textContent, innerText, and innerHTML. Each behaves differently, and picking the wrong one leads to security vulnerabilities or unexpected display issues.
Reading Text from DOM Elements
Before changing text, you need to understand how to read it. Every DOM element exposes text-related properties that return the element's content as a string.
// Given this HTML:
// <p id="greeting">Hello, <strong>World</strong>!</p>
const paragraph = document.getElementById("greeting");
// textContent: returns ALL text, including hidden elements
console.log(paragraph.textContent); // "Hello, World!"
// innerText: returns only VISIBLE text (respects CSS)
console.log(paragraph.innerText); // "Hello, World!"
// innerHTML: returns raw HTML markup
console.log(paragraph.innerHTML); // "Hello, <strong>World</strong>!"The difference becomes clear when CSS hides part of the content:
// Given this HTML:
// <div id="info">
// Visible text
// <span style="display: none;">Hidden text</span>
// </div>
const info = document.getElementById("info");
console.log(info.textContent); // "Visible text Hidden text"
console.log(info.innerText); // "Visible text"
console.log(info.innerHTML); // Full HTML string with the spanUsing textContent to Change Text
The textContent property is the fastest and safest way to set plain text. It replaces everything inside the element with a text node.
const heading = document.querySelector("h1");
// Set new text content
heading.textContent = "Welcome to RuneHub";
// Any HTML tags are treated as plain text, not rendered
heading.textContent = "<em>Welcome</em> to RuneHub";
// Displays literally: <em>Welcome</em> to RuneHubThis auto-escaping behavior makes textContent safe against XSS attacks:
// User input that contains a script tag
const userInput = '<script>alert("hacked")</script>';
// SAFE: textContent escapes the HTML
document.getElementById("output").textContent = userInput;
// Displays: <script>alert("hacked")</script> (as visible text)When to Use textContent
| Scenario | Use textContent? |
|---|---|
| Setting plain text from user input | Yes (safe from XSS) |
| Reading all text including hidden elements | Yes |
| Building accessible content | Yes (screen readers read all text) |
| Updating counters, labels, messages | Yes |
| Inserting HTML markup | No (use innerHTML or DOM methods) |
Using innerText to Change Text
The innerText property works similarly to textContent but accounts for CSS styling. It only reads visible text and triggers a reflow when accessed, making it slower.
const status = document.querySelector(".status");
// Set text (behaves like textContent for setting)
status.innerText = "Online";
// Multi-line text preserves line breaks
status.innerText = "Line 1\nLine 2\nLine 3";
// Creates actual <br> elements in the rendered outputThe key difference from textContent is how innerText handles whitespace and visibility:
// Given: <div id="code"> function hello() { } </div>
const el = document.getElementById("code");
// textContent preserves all whitespace exactly
console.log(el.textContent); // " function hello() { } "
// innerText collapses whitespace like the browser renders it
console.log(el.innerText); // "function hello() { }"Performance Difference
// textContent is significantly faster because it doesn't trigger layout
const element = document.getElementById("target");
// Fast: just reads/writes the text node
console.time("textContent");
for (let i = 0; i < 10000; i++) {
element.textContent = `Count: ${i}`;
}
console.timeEnd("textContent"); // ~20ms
// Slower: triggers reflow on every read
console.time("innerText");
for (let i = 0; i < 10000; i++) {
element.innerText = `Count: ${i}`;
}
console.timeEnd("innerText"); // ~150msUsing innerHTML to Change Content
The innerHTML property reads and writes raw HTML markup. Unlike textContent, it parses HTML tags and renders them.
const container = document.getElementById("container");
// Set HTML content
container.innerHTML = "<h2>New Title</h2><p>New paragraph with <strong>bold</strong> text.</p>";
// Clear all content
container.innerHTML = "";
// Append HTML (replaces existing content!)
container.innerHTML = "<ul><li>Item 1</li><li>Item 2</li></ul>";The Security Risk of innerHTML
Using innerHTML with user input creates Cross-Site Scripting (XSS) vulnerabilities:
// DANGEROUS: Never put user input directly into innerHTML
const userComment = '<img src="x" onerror="alert(document.cookie)">';
// This executes the attacker's JavaScript!
document.getElementById("comments").innerHTML = userComment;
// SAFE alternative: use textContent for user input
document.getElementById("comments").textContent = userComment;
// Displays the HTML as visible text, doesn't execute itComparison Table: textContent vs innerText vs innerHTML
| Feature | textContent | innerText | innerHTML |
|---|---|---|---|
| Returns | All text nodes (including hidden) | Visible text only | Full HTML markup |
| Sets | Plain text (HTML escaped) | Plain text (line breaks to <br>) | Parsed HTML |
| Speed | Fastest | Slowest (triggers reflow) | Medium |
| XSS safe | Yes (auto-escapes HTML) | Yes (auto-escapes HTML) | No (parses HTML) |
| Preserves whitespace | Yes (raw whitespace) | No (collapses like CSS) | Yes (raw HTML) |
| Removes child elements | Yes (replaces all) | Yes (replaces all) | Yes (replaces all) |
| Best for | Setting plain text, reading all text | Reading visible text | Building complex HTML |
Practical Patterns for Changing Text
Pattern 1: Live Character Counter
const textarea = document.querySelector("#message");
const counter = document.querySelector("#char-count");
const maxLength = 280;
textarea.addEventListener("input", () => {
const remaining = maxLength - textarea.value.length;
counter.textContent = `${remaining} characters remaining`;
// Change color based on remaining count
if (remaining < 20) {
counter.style.color = "red";
} else if (remaining < 50) {
counter.style.color = "orange";
} else {
counter.style.color = "green";
}
});Pattern 2: Dynamic Status Messages
function showStatus(element, type, message) {
// Use textContent for safety (message might come from server)
element.textContent = message;
// Update visual styling
element.className = `status status-${type}`;
}
const statusBar = document.getElementById("status");
showStatus(statusBar, "success", "File uploaded successfully!");
showStatus(statusBar, "error", "Upload failed. Please try again.");
showStatus(statusBar, "loading", "Uploading...");Pattern 3: Building a List from Data
function renderUserList(users) {
const list = document.getElementById("user-list");
// Clear existing content
list.innerHTML = "";
// Build list items safely using DOM methods
users.forEach(user => {
const li = document.createElement("li");
li.className = "user-item";
const name = document.createElement("strong");
name.textContent = user.name; // Safe: textContent escapes HTML
const role = document.createElement("span");
role.textContent = ` (${user.role})`;
li.appendChild(name);
li.appendChild(role);
list.appendChild(li);
});
}
renderUserList([
{ name: "Alice", role: "Admin" },
{ name: "Bob", role: "Editor" },
{ name: "Charlie", role: "Viewer" }
]);Pattern 4: Toggle Show/Hide with Text Update
const toggleBtn = document.getElementById("toggle-btn");
const content = document.getElementById("collapsible");
toggleBtn.addEventListener("click", () => {
const isHidden = content.style.display === "none";
content.style.display = isHidden ? "block" : "none";
toggleBtn.textContent = isHidden ? "Hide Details" : "Show Details";
});Common Mistakes to Avoid
Mistake 1: Using innerHTML for Plain Text
const username = getUserInput(); // Could be malicious
// WRONG: XSS vulnerability
document.getElementById("welcome").innerHTML = `Hello, ${username}!`;
// CORRECT: Use textContent for user-generated content
document.getElementById("welcome").textContent = `Hello, ${username}!`;Mistake 2: Forgetting innerHTML Replaces Everything
const list = document.getElementById("items");
// WRONG: Each assignment overwrites all previous content
list.innerHTML = "<li>Item 1</li>";
list.innerHTML = "<li>Item 2</li>"; // Item 1 is gone!
// CORRECT: Use += to append (though DOM methods are preferred)
list.innerHTML += "<li>Item 1</li>";
list.innerHTML += "<li>Item 2</li>";
// BEST: Use DOM creation methods
const li = document.createElement("li");
li.textContent = "Item 1";
list.appendChild(li);Mistake 3: Using innerText When You Need textContent
// Reading content inside a <pre> or formatted element
const codeBlock = document.querySelector("pre code");
// WRONG: innerText collapses whitespace, breaking code formatting
const code = codeBlock.innerText;
// CORRECT: textContent preserves all whitespace
const code2 = codeBlock.textContent;Real-World Example: Search Results with Highlighting
This example combines textContent for safety and innerHTML for controlled formatting:
function displaySearchResults(results, query) {
const container = document.getElementById("search-results");
const countElement = document.getElementById("result-count");
// Use textContent for the count (no HTML needed)
countElement.textContent = `${results.length} results for "${query}"`;
// Clear previous results
container.innerHTML = "";
results.forEach(result => {
const article = document.createElement("article");
article.className = "search-result";
const title = document.createElement("h3");
// Safely highlight the query in the title
title.innerHTML = highlightMatch(escapeHtml(result.title), query);
const snippet = document.createElement("p");
snippet.innerHTML = highlightMatch(escapeHtml(result.snippet), query);
const link = document.createElement("a");
link.href = result.url;
link.textContent = result.url; // Safe: textContent
article.appendChild(title);
article.appendChild(snippet);
article.appendChild(link);
container.appendChild(article);
});
}
// Escape HTML entities to prevent XSS
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// Highlight matching text (safe because input is already escaped)
function highlightMatch(escapedHtml, query) {
const regex = new RegExp(`(${escapeRegex(query)})`, "gi");
return escapedHtml.replace(regex, "<mark>$1</mark>");
}
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Usage
displaySearchResults(
[
{ title: "JavaScript DOM Guide", snippet: "Learn DOM manipulation...", url: "/tutorials/dom-guide" },
{ title: "DOM Events Tutorial", snippet: "Handle DOM events...", url: "/tutorials/dom-events" }
],
"DOM"
);Rune AI
Key Insights
- Default to textContent: It is the fastest and safest property for reading and writing plain text in DOM elements
- XSS prevention: Never use
innerHTMLwith unsanitized user input; usetextContentor escape HTML entities first - Performance matters:
textContentavoids layout reflow;innerTexttriggers reflow on every access and is roughly 7x slower - Replacement behavior: All three properties replace existing content entirely when setting a value; use DOM methods to append
- Use the right tool:
textContentfor plain text,innerTextfor visible text,innerHTMLfor HTML markup, andcreateElementfor safe dynamic content
Frequently Asked Questions
What is the safest way to set text from user input?
Does textContent remove child elements?
When should I use innerText instead of textContent?
Is innerHTML always dangerous?
How do I append text without replacing existing content?
Conclusion
Changing text content in the DOM comes down to choosing the right property for the job. Use textContent as your default because it is fast, safe from XSS, and works predictably. Use innerText only when you need text that matches the visual rendering on screen. Reserve innerHTML for situations where you need to insert HTML markup, and always escape user input before passing it to innerHTML. For building complex dynamic content, prefer DOM creation methods (createElement, appendChild) over string-based HTML injection.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.