English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM textContent Attribute

HTML DOM Element Object

textContentattribute sets or returns the text content of the specified node and all its child nodes.

Setting textContent on a node will remove all child nodes of the node and replace them with a single text node with the given text.

The textContent attribute is similar toinnerTextattributes, but there are some differences:

  • textContent returnsallreturns the text content of the element, while innerText returnsexcept <script> and <style> elementsexceptof all elements.

  • innerText does not return text hidden in CSS (textContent does return)

To set or return the HTML content of the element, useinnerHTMLAttribute.

Syntax:

Returns the text content of the node:

node.textContent

Set the text content of the node:

node.textContent = text
var x = document.getElementById("para").textContent;
Test to see‹/›

Browser Compatibility

All browsers fully support the textContent attribute:

Attribute
textContentisisisisis

Attribute Value

ValueDescription
textSpecify the text content of the specified node

Technical Details

Return value:A string representing the text of the node and all its child nodes. If the element is a document, document type, or not, it returns null
DOM Version:DOM Level3

More Examples

Change the text content of the <p> element using id="para":

var x = document.getElementById("para");
x.textContent = "HELLO WORLD";
Test to see‹/›

Returns all text content of the DIV element:

var x = document.getElementById("container").textContent;
Test to see‹/›

This example demonstrates the differences between innerText, innerHTML, and textContent:

<p id="x">This element has additional spacing and contains a <span>span element</span>.</p>
<script>
function getInnerText() {
alert(document.getElementById("x").innerText);
}
function getInnerHTML() {
alert(document.getElementById("x").innerHTML);
}
function getTextContent() {
alert(document.getElementById("x").textContent);
}
</script>
Test to see‹/›

The innerText property only returns text, without spaces and internal element tags.

The innerHTML property returns text with spaces and internal element tags.

The textContent property returns spaced text but without internal element tags.

Related References

HTML DOM Reference:HTMLElement.innerText property

HTML DOM Reference:element.innerHTML property

HTML DOM Element Object