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
var text = element.textContent; element.textContent = "New text";
Sample Code
<p id="pilot"><strong>Ayanami Rei</strong> — <em>NERV</em></p> <div id="profile"> <span>Ikari Shinji</span> <span style="display: none;">Unit-01 Pilot</span> </div> <p id="output"></p>
This produces the following output:
var pilot = document.getElementById("pilot");
console.log(pilot.textContent); // Outputs "Ayanami Rei — NERV" (no tags)
// Pattern 2: textContent includes hidden elements too
var profile = document.getElementById("profile");
console.log(profile.textContent); // Outputs "Ikari ShinjiUnit-01 Pilot" (hidden text is included)
// Pattern 3: Set text (HTML tags are displayed as literal characters)
var output = document.getElementById("output");
output.textContent = "Eva Unit-01 Pilot: <strong>Ikari Shinji</strong>";
// The page displays: Eva Unit-01 Pilot: <strong>Ikari Shinji</strong>
// Pattern 4: Safely display user input (XSS prevention)
var userInput = '<img src=x onerror="alert(1)">';
output.textContent = userInput; // Tags are escaped and displayed as safe literal 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.