JavaScriptDOM and events

Node.textContent

Reads or sets all of an element’s text, without HTML markup.

Returns
A string with the text of the element and all of its descendants.
On this page

Example

#
JavaScript
const welcome = document.querySelector('#welcome')

console.log(welcome.textContent)
console.log(welcome.children.length)

welcome.textContent = 'All tasks complete!'
console.log(welcome.children.length)
Console
Welcome, Emma! You have 3 new tasks.
2
0

Definition and usage

#

The textContent property returns the element’s text together with the text of every nested element, joined into one string. HTML markup is skipped, leaving just the content, including whitespace and newlines from the HTML code.

Assigning to textContent removes all of the element’s content and inserts a single text node in its place. The text is inserted literally: < and > characters don’t create markup, they just show up on screen. That makes it a safe way to display data from a user.

The similar innerText property takes styles into account: it skips hidden elements and mirrors the line breaks visible on screen. It’s slower, though, since it requires computing the page layout. For plain text assignment, go with textContent.

Syntax

#
Syntax
const text = element.textContent
element.textContent = newText

More examples

#
Text is inserted literally
JavaScript
const comment = document.querySelector('#comment')

comment.textContent = 'Use the <strong> tag to make text bold'

console.log(comment.children.length)
console.log(comment.innerHTML)
Console
0
Use the &lt;strong&gt; tag to make text bold
Whitespace from the HTML code
JavaScript
const skills = document.querySelector('#skills')

console.log(JSON.stringify(skills.textContent))
console.log(skills.textContent.trim().split(/\s+/))
Console
"\n HTML\n CSS\n"
['HTML', 'CSS']

Indentation and newlines from the HTML code are text too, so they end up in textContent. JSON.stringify() shows them as \n and spaces, and trim() removes them from the start and end.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To display text from a user, use textContent, not innerHTML. This protects against code injection (XSS attacks).
  • The text you read might contain whitespace and newlines from the HTML code. Clean it up with trim() if needed.
  • Assigning element.textContent = "" is a quick way to clear an element.

Related entries

#

Spotted a mistake or missing an example? Write to us.