textContent
Reading textContent
from a node
textContent
from a nodeTo get the text content of a node and its descendants, you use the textContent
property:
Suppose that you have the following HTML snippet:
The following example uses the textContent
property to get the text of the <div>
element:
How it works.
First, select the
div
element with the id note by using thegetElementById()
method.Then, display the text of the node by accessing the
textContent
property.
Output:
As you can see clearly from the output, the textContent
property returns the concatenation of the textContent
of every child node, excluding comments (and also processing instructions).
textContent
vs. innerText
textContent
vs. innerText
On the other hand, the innerText
takes the CSS style into account and returns only human-readable text. For example:
Output:
As you can see, the hidden text and comments are not returned.
Since the innerText
property uses the up-to-date CSS to compute the text, accessing it will trigger a reflow, which is computationally expensive.
A reflow occurs when a web brower needs to process and draw parts or all of a webpage again.
Setting textContent
for a node
textContent
for a nodeBesides reading textContent
, you can also use the textContent
property to set the text for a node:
When you set textContent
on a node, all the node’s children will be removed and replaced by a single text node with the newText
value. For example:
Summary
Use the
textContent
property to return the concatenation of thetextContent
of every child node. You can use it to set a text for a node.The
innerText
returns the human-readable text that takes CSS into account.
Last updated