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.
heading.textContent = "Hello"; const text = article.textContent;
Try it
Syntax
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: nonestill contribute. If you need the text as the user sees it, useinnerText. - 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 makestextContentthe default choice for displaying untrusted text. - Fast. It needs no layout calculation, so it is cheaper than
innerTextin loops. - Document text.
document.textContentisnull; readdocument.documentElement.textContentinstead.
Browser support
Supported in every browser.
Related
HTMLElement.innerTextโ rendered, CSS-aware textElement.innerHTMLโ markup getter and setterdocument.createTextNode()โ create a text node directly- Lesson: Creating and changing elements