HTML Element .textContent Since: DOM Level 3(2004)
Gets or sets the text content of an HTML element. HTML tags are not interpreted — the content is treated as plain text.
Syntax
// Get the text content. var text = element.textContent; // Set the text content. element.textContent = "New text";
Sample Code
<p id="sample">Hello<span>World</span></p>
var el = document.querySelector("#sample");
// Retrieves only the text, ignoring HTML tags.
console.log(el.textContent); // Outputs "HelloWorld".
// Sets the text content. HTML tags are displayed as literal strings, not interpreted as HTML.
el.textContent = "New <span>text</span>";
// The page displays: New text
Difference between textContent and innerHTML
| Property | Description |
|---|---|
| textContent | Does not interpret HTML tags. Treats the value as plain text, making it safe to use. Suitable for displaying user-supplied input. |
| innerHTML | Interprets HTML tags. Use it when you need to insert HTML dynamically. However, inserting user input directly can allow malicious scripts to run, which is an XSS vulnerability. See the element.innerHTML page for details. |
Overview
element.textContent is a property for getting or setting the text content of an HTML element. When getting the value, it ignores all child element tags and returns only the concatenated plain text.
When setting the value, even if the string contains HTML tags, those tags are displayed as literal characters and are not interpreted as HTML. Because of this behavior, element.textContent is safer than element.innerHTML when displaying user-supplied input on the page.
If you need to insert content that includes HTML, use element.innerHTML instead.
Browser Compatibility
2 or earlier ×
8 or earlier ×
8 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.