.textContent
Example
const name = new URLSearchParams(location.search).get('name');
greeting.innerHTML = `Hello, ${name}`;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
textContenton a button and removing its icon. - Expecting
textContentto skip text inside<script>or<style>elements.
Key points
- Plain text from users or APIs is set with
textContent, notinnerHTML. textContentis 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.