HTML DOM Element textContent Property

Definition and Usage

textContent property to set or return the text content of a specified node, as well as all its descendants.

If you set textContent property, which will remove all child nodes and be replaced by a single text node containing the given string.

Tip:Sometimes, this property can be used instead of nodeValue property, but remember that this property will also return the text of all child nodes.

See also:

innerText property

innerHTML property

Instance

Example 1

Return the text content of the element:

let text = element.textContent;

Try it yourself

Example 2

Change the text content of the <p> element with id="demo":

element.textContent = "I have changed!";

Try it yourself

Example 3

Get all text content of the <ul> element with id="myList":

let text = document.getElementById("myList").textContent;

Try it yourself

Syntax

Return the text content of a node:

element.textContent

or

node.textContent

Set the text content of a node:

element.textContent = text
node.textContent = text

Attribute Value

Value Description
text Text content of an element or node.

Return Value

Type Description
String

Text content of the element and all its descendants.

Returns null if the element is document, document type, or notation.

Difference between innerHTML, innerText, and textContent

The innerText property returns:

Returns only the text content of the element and all its children, without CSS hidden text spacing and tags, except for <script> and <style> elements.

The innerHTML property returns:

Text content of the element, including all whitespace and internal HTML tags.

The textContent property returns:

Text content of the element and all its descendants, including whitespace and CSS hidden text, but without tags.

HTML Example

<p id="myP">   This element has extra spacing     and contains <span>a span element</span>.</p>

JavaScript Examples

let text = document.getElementById("myP").innerText;
let text = document.getElementById("myP").innerHTML;
let text = document.getElementById("demo").textContent;

Try it yourself

In the above example:

The innerText property returns:

This element has extra spacing and contains a span element.

The innerHTML property returns:

   This element has extra spacing and contains <span>a span element</span>.

The textContent property returns:

   This element has extra spacing and contains a span element.

Browser support

element.textContent It is a DOM Level 3 (2004) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support