What is the difference between innerHTML and textContent
· Category: JavaScript
Short answer
innerHTML parses and inserts HTML markup, while textContent sets plain text without parsing, making it safer and faster for non-HTML content.
Key differences
| Aspect | innerHTML | textContent |
|---|---|---|
| Parsing | Parses HTML | No parsing |
| Security | Vulnerable to XSS | Safe from HTML injection |
| Performance | Slower (parser involved) | Faster |
| Inserts tags | Yes | No (escaped) |
When to use each
- Use
textContentfor user-generated or plain text to prevent XSS. - Use
innerHTMLonly with trusted markup, or sanitize content first.
Example
const el = document.querySelector("#output");
el.textContent = "<script>alert(1)</script>"; // renders as text
el.innerHTML = "<strong>Bold</strong>"; // renders as HTML
Why it matters
Choosing the wrong property opens your application to cross-site scripting attacks. Default to textContent and treat innerHTML as a privileged operation.