JavaScript: textContent
The textContent property reads or replaces an element’s plain text without parsing the value as HTML.
What you will learn
- How to read and update text content
- How textContent differs from innerHTML
- Why plain text is a safer default for user-controlled values
Minimal example
const message = document.querySelector('#message');
const name = 'A <visitor>';
if (message) message.textContent = `Hello, ${name}`;The characters are displayed as text, not interpreted as an element or script. Use innerHTML only when you intentionally create trusted markup and understand the escaping requirements.
Common mistakes
- Do not use
innerHTMLfor untrusted input; it can create an injection vulnerability. - Remember that setting textContent replaces the element’s child nodes.
- Check that the element exists before updating it.