Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

Node.textContent

Reference for Node.textContent: read all the text inside a node, replace children with plain text safely, and how it differs from innerText and innerHTML.

The textContent property returns the text inside a node and all its descendants, as one string. Setting it removes every child of the node and puts a single text node in their place. Because the string is never parsed as HTML, textContent is the safe way to show text that came from a user.

It reads the raw text of the DOM tree. It does not care about CSS, so hidden text is included, and it does not add line breaks between blocks.

JavaScript
heading.textContent = "Hello";
const text = article.textContent;

Try it

textContent ignores markup and CSS
Safe output of user text

Syntax

JavaScript
const text = node.textContent;
node.textContent = newText;
Name Description
newText A string. Any other value is converted to a string; null becomes an empty string.

Return value (getter): a string for elements and document fragments, the node's data for text and comment nodes, and null for document and doctype nodes.

Usage notes

  • What is included. The text of every descendant text node, joined together, including whitespace between tags and the contents of <script> and <style> elements. Comments and processing instructions of descendants are skipped.
  • CSS is ignored. Elements hidden with display: none still contribute. If you need the text as the user sees it, use innerText.
  • No line breaks between blocks. Adjacent paragraphs run together unless the source contains newline characters.
  • Setting replaces children. All existing child nodes are removed, so listeners on them are lost. Assigning "" empties the element.
  • No HTML parsing. <b> in the string appears literally on the page. This is what makes textContent the default choice for displaying untrusted text.
  • Fast. It needs no layout calculation, so it is cheaper than innerText in loops.
  • Document text. document.textContent is null; read document.documentElement.textContent instead.

Browser support

Supported in every browser.