docs.rodeo

MDN Web Docs mirror

Node: textContent property

{{APIRef("DOM")}} 

The textContent property of the {{domxref("Node")}}  interface represents the text content of the node and its descendants.

[!NOTE] textContent and {{domxref("HTMLElement.innerText")}}  are easily confused, but the two properties are different in important ways.

Value

A string, or null. Its value depends on the situation:

[!WARNING] Setting textContent on a node removes all of the node’s children and replaces them with a single text node with the given string value.

Differences from innerText

Don’t get confused by the differences between Node.textContent and {{domxref("HTMLElement.innerText")}} . Although the names seem similar, there are important differences:

Differences from innerHTML

{{domxref("Element.innerHTML")}}  gets or sets HTML, as its name indicates. We advise against using innerHTML to get or set text inside an element because it deals with raw HTML rather than plain text and can be susceptible to {{glossary("Cross-site_scripting", "XSS attacks")}} . Even if you are sure that the text never contains HTML syntax, it is still less semantic and slower because it needs to invoke the HTML parser.

Examples

Start with 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!'

If you prefer to set the element’s text content, you can do:

document.getElementById("divA").textContent = "This text is different!";
// The HTML for divA is now:
// <div id="divA">This text is different!</div>

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN