textContent from a node
To get the text content of a node and its descendants, you use the
let text = node.textContent;
Suppose that you have the following HTML snippet:
The following example uses the
textContent property to get the text of the
let note = document.getElementById('note'); console.log(note.textContent);
How it works.
- First, select the
divelement with the id note by using the
- Then, display the text of the node by accessing the
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).
On the other hand, the
innerText takes the CSS style into account and returns only human-readable text. For example:
let note = document.getElementById('note'); console.log(note.innerText);
As you can see, the hidden text and comments are not returned.
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 browser needs to process and draw parts or all of a webpage again.
textContent for a node
textContent, you can also use the
textContent property to set the text for a node:
node.textContent = newText;
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:
let note = document.getElementById('note'); note.textContent = 'This is a note';
- Use the
textContentproperty to return the concatenation of the
textContentof every child node. You can use it to set a text for a node.
innerTextreturns the human-readable text that takes CSS into account.