References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript textContent property

Property JavaScript All modern browsers Updated
Quick answer

The textContent property gets or sets the plain text inside an element. el.textContent = "Hello" sets its text, escaping any HTML so tags show as literal characters. It's the safe, fast choice for displaying text — unlike innerHTML, it can't inject scripts.

Overview

textContent is the plain-text counterpart to innerHTML. Reading it gives you all the text inside an element (tags stripped out); setting it replaces the contents with text only. Crucially, any HTML in the value is treated as literal characters — assign "<b>hi</b>" and the page shows the angle brackets, it doesn't make bold text.

That escaping is exactly why textContent is the safe default for putting data on the page. User names, comments, search terms, anything from outside your code — set them with textContent and there's no way for embedded markup to run. It sidesteps the XSS risk that makes innerHTML dangerous, and it's a little faster too, since there's no HTML parsing.

It's close to innerText but not identical, and the difference matters. textContent returns all text including hidden elements and respects the raw source; innerText is layout-aware — it reflects what's actually visible and triggers a reflow to figure that out. For reliable, performant text access, prefer textContent unless you specifically need the rendered-visibility behavior.

Syntax

const text = element.textContent;   // read (tags stripped)
element.textContent = "Plain text"; // set (HTML is escaped)

Example

Live example
<p id="demo" style="font:15px system-ui"></p>
<script>
  const p = document.getElementById('demo');

  // HTML is shown literally, not rendered (safe)
  p.textContent = 'This <b>stays</b> as plain text';
</script>

Best practices

  • Use textContent as the default for inserting text — it's safe against injection.
  • Reach for innerHTML only when you truly need to insert trusted HTML markup.
  • Prefer textContent over innerText unless you need visibility-aware text, which is slower.
  • Setting it replaces all existing children with a single text node.

Frequently asked questions

What is the difference between textContent and innerHTML?
textContent sets or reads plain text (HTML is escaped); innerHTML parses the string as HTML. Use textContent for safe text and innerHTML for trusted markup.
What is the difference between textContent and innerText?
textContent returns all text from the source, including hidden elements, and is faster; innerText returns only visible text and triggers a layout reflow.
Is textContent safe from XSS?
Yes. It treats everything as plain text, so embedded HTML or scripts can't run. It's the recommended way to display user-supplied data.
How do I get the text of an element without the HTML tags?
Read element.textContent, which returns the text with all tags removed.