HTML DOM Element textContent

Examples

Return the text content of an element:

let text = element.textContent;
Try it Yourself »

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

element.textContent = "I have changed!";
Try it Yourself »

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

let text = document.getElementById("myList").textContent;
Try it Yourself »

Description

The textContent property sets or returns the text content of the specified node, and all its descendants.

Note

When you set the textContent property, all child nodes are removed and replaced by only one new text node.

See Also:

The innerText Property

The innerHTML Property

The Differences Between
innerHTML, innerText and textContent

See below


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

Property Value

Property Description
text The text content of the element or node.

Return Value

Type Description
StringThe text content of the element and all its descendants.
Returns null if the element is a document, a document type, or a notation.


The Differences Between
innerHTML, innerText and textContent

The innerHTML property returns:
The text content of the element, including all spacing and inner HTML tags.
The innerText property returns:
Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.
The textContent property returns:
The text content of the element and all descendaces, with spacing 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 example above:

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 is a DOM Level 3 (2004) feature.

It is fully supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.