textContent property of the
interface represents the text content of the node and its descendants.
A string, or
null. Its value depends on the situation:
If the node is a
documentor a doctype,
Note: To get all of the text and CDATA data for the whole document, use
If the node is a CDATA section,
a comment, a processing instruction,
or a text node,
textContentreturns, or sets, the text inside the node, i.e., the
For other node types,
textContentreturns the concatenation of the
textContentof every child node, excluding comments and processing instructions. (This is an empty string if the node has no children.)
textContent on a node removes all of the node's children
and replaces them with a single text node with the given string value.
Don't get confused by the differences between
HTMLElement.innerText. Although the names seem similar, there are
textContentgets the content of all elements, including
<style>elements. In contrast,
innerTextonly shows "human-readable" elements.
textContentreturns every element in the node. In contrast,
innerTextis aware of styling and won't return the text of "hidden" elements.
innerTexttakes CSS styles into account, reading the value of
innerTexttriggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)
- Moreover, since
innerTextremove child nodes when altered, but altering
innerTextin Internet Explorer (version 11 and below) also permanently destroys all descendant text nodes. It is impossible to insert the nodes again into any other element or into the same element after doing so.
Element.innerHTML returns HTML, as its name indicates. Sometimes people
innerHTML to retrieve or write text inside an element, but
textContent has better performance because its value is not parsed as
textContent can prevent XSS attacks.
Given this HTML fragment:
<div id="divA">This is <span>some</span> text!</div>
... you can use
textContent to get the element's text content:
let text = document.getElementById('divA').textContent; // The text variable is now: 'This is some text!'
... or set the element's text content:
document.getElementById('divA').textContent = 'This text is different!'; // The HTML for divA is now: // <div id="divA">This text is different!</div>
|DOM Standard (DOM)|
BCD tables only load in the browser