Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. HTML Element .textContent

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.

View sample page

Difference between textContent and innerHTML

PropertyDescription
textContentDoes not interpret HTML tags. Treats the value as plain text, making it safe to use. Suitable for displaying user-supplied input.
innerHTMLInterprets 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

Chrome Chrome
49+
Firefox Firefox
57+
Safari Safari
18+
2 or earlier ×
Edge Edge
80+
11 or earlier ×
IE IE
11+
8 or earlier ×
Opera Opera
48+
8 or earlier ×
iOS Safari iOS Safari
18+
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .