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.

JavaScriptbeginner
9 min read

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.

javascriptjavascript
// 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:

javascriptjavascript
// 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 span

Using 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.

javascriptjavascript
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 RuneHub

This auto-escaping behavior makes textContent safe against XSS attacks:

javascriptjavascript
// 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

ScenarioUse textContent?
Setting plain text from user inputYes (safe from XSS)
Reading all text including hidden elementsYes
Building accessible contentYes (screen readers read all text)
Updating counters, labels, messagesYes
Inserting HTML markupNo (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.

javascriptjavascript
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 output

The key difference from textContent is how innerText handles whitespace and visibility:

javascriptjavascript
// 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

javascriptjavascript
// 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"); // ~150ms

Using innerHTML to Change Content

The innerHTML property reads and writes raw HTML markup. Unlike textContent, it parses HTML tags and renders them.

javascriptjavascript
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:

javascriptjavascript
// 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 it

Comparison Table: textContent vs innerText vs innerHTML

FeaturetextContentinnerTextinnerHTML
ReturnsAll text nodes (including hidden)Visible text onlyFull HTML markup
SetsPlain text (HTML escaped)Plain text (line breaks to <br>)Parsed HTML
SpeedFastestSlowest (triggers reflow)Medium
XSS safeYes (auto-escapes HTML)Yes (auto-escapes HTML)No (parses HTML)
Preserves whitespaceYes (raw whitespace)No (collapses like CSS)Yes (raw HTML)
Removes child elementsYes (replaces all)Yes (replaces all)Yes (replaces all)
Best forSetting plain text, reading all textReading visible textBuilding complex HTML

Practical Patterns for Changing Text

Pattern 1: Live Character Counter

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
// 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:

javascriptjavascript
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

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 innerHTML with unsanitized user input; use textContent or escape HTML entities first
  • Performance matters: textContent avoids layout reflow; innerText triggers 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: textContent for plain text, innerText for visible text, innerHTML for HTML markup, and createElement for safe dynamic content
RunePowered by Rune AI

Frequently Asked Questions

What is the safest way to set text from user input?

Use `textContent`. It automatically escapes any HTML tags in the string, treating them as plain text instead of executable markup. This prevents Cross-Site Scripting (XSS) attacks where an attacker injects malicious code through user input fields.

Does textContent remove child elements?

Yes. Setting `textContent` on an element replaces all its children (including other elements) with a single text node. If you have a `<div>` containing paragraphs, headings, and spans, setting `textContent` removes all of them and replaces everything with plain text.

When should I use innerText instead of textContent?

Use `innerText` when you need text that matches what the user actually sees on screen. It respects CSS visibility, collapses whitespace like the browser renders it, and converts `<br>` elements to newline characters. This is useful when copying visible text or reading display values.

Is innerHTML always dangerous?

No, `innerHTML` is safe when you control the content being inserted. Using it with hardcoded strings or properly escaped server data is fine. It becomes dangerous only when you insert unsanitized user input. If you must use `innerHTML` with dynamic data, always escape HTML entities first using a function like `escapeHtml`.

How do I append text without replacing existing content?

For plain text, read the current `textContent`, concatenate your new text, and set it back: `el.textContent += " new text"`. For HTML content, use DOM methods like `createElement` and `appendChild` instead of `innerHTML +=` because the concatenation approach re-parses and recreates all existing child nodes, which destroys event listeners.

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.