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.
Example
#const welcome = document.querySelector('#welcome')
console.log(welcome.textContent)
console.log(welcome.children.length)
welcome.textContent = 'All tasks complete!'
console.log(welcome.children.length)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
#const text = element.textContent
element.textContent = newTextMore examples
#const comment = document.querySelector('#comment')
comment.textContent = 'Use the <strong> tag to make text bold'
console.log(comment.children.length)
console.log(comment.innerHTML)const skills = document.querySelector('#skills')
console.log(JSON.stringify(skills.textContent))
console.log(skills.textContent.trim().split(/\s+/))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, notinnerHTML. 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
#- innerHTML vs textContentinnerHTML reads and sets an element’s HTML markup, parsing the string into new elements, while textContent reads and sets plain text, with no markup.
- Element.innerHTMLReads or replaces an element’s content as HTML code.
- document.createElement()Creates a new HTML element with the given tag name, ready to be inserted into the page.
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- String.prototype.trim()Removes whitespace from both ends of a string: spaces, tabs, and newline characters.
Spotted a mistake or missing an example? Write to us.