.textContent

Term side of the Card.
Topic: Object on Page
Unit title: .textContent
Categories: Property
Explanation side of the Card

Explanation: The browser API property that gets or sets the text content of an HTML element. It returns the plain text inside the element and its child elements, excluding any HTML tags.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 3.
Availability: 

Example

Wrongjs
const name = new URLSearchParams(location.search).get('name');
greeting.innerHTML = `Hello, ${name}`;
Rightjs
const name = new URLSearchParams(location.search).get('name');
greeting.textContent = `Hello, ${name}`;

textContent shows any markup from the URL as text, which closes a reflected XSS hole.

Common mistakes

  • Setting textContent on a button and removing its icon.
  • Expecting textContent to skip text inside <script> or <style> elements.

Key points

  • Plain text from users or APIs is set with textContent, not innerHTML.
  • textContent is not set on an element whose child elements must stay, because it replaces them all.

Interview questions

textContent vs innerText?

textContent returns all text, including hidden elements, without triggering layout. innerText returns only rendered text and is slower.

Can textContent be null?

Only for the document and doctype nodes. For elements it is always a string, empty when there is no text.

How do I change text without removing child elements?

Wrap the text in its own <span> and set that span's textContent.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy