# .textContent

> The `.textContent` JS browser API property represents the text content of a node and all its descendants.

## How do I safely set the text of an element in JavaScript?

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.

- Topic: Object on Page
- Type: property
- Browser support: Chrome 1+, Chrome Android 18+, Edge 12+, Firefox 1+, Firefox Android 4+, Safari 3+, Safari iOS 1+

## Example

Wrong:

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

Right:

```js
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`.

## Related cards

- [.innerText](https://wonderium.dev/js/inner-text.md)
- [.innerHTML](https://wonderium.dev/js/inner-html.md)
- [Reflected XSS](https://wonderium.dev/web/xss-reflected.md)
- [URLSearchParams](https://wonderium.dev/js/url-search-params.md)
- [Element](https://wonderium.dev/js/element.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/text-content
- Last updated: 2026-11-25
