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 »
The textContent
property sets or returns the text content of the specified node, and all its descendants.
When you set the textContent property, all child nodes are removed and replaced by only one new text node.
See below
Return the text content of a node:
element.textContent
node.textContent
Set the text content of a node:
element.textContent =
text
node.textContent =
text
Property | Description |
text | The text content of the element or node. |
Type | Description |
String | The text content of the element and all its descendants. Returns null if the element is a document, a document type, or a notation. |
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. |
<p id="myP"> This element has extra spacing and contains <span>a span element</span>.</p>
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. |
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!