What is the difference between `innerHTML` and `textContent`?
TL;DR
innerHTML gets or replaces serialized HTML markup, so assigning to it invokes the HTML parser and creates elements. textContent gets or replaces text and treats < and > as characters. Use textContent for untrusted plain text. Use innerHTML only when HTML is intentionally required and the value is trusted or processed by an appropriate HTML sanitizer; assigning arbitrary user input creates an XSS sink.
// Example of innerHTMLelement.innerHTML = '<strong>Bold Text</strong>'; // Renders as bold text// Example of textContentelement.textContent = '<strong>Bold Text</strong>'; // Renders as plain text: <strong>Bold Text</strong>
Text insertion versus HTML parsing
The APIs send the same string through different browser pipelines.
Use textContent for plain text. Use innerHTML only when HTML interpretation is intentional and the value comes from a trusted or correctly sanitized source.
Difference between innerHTML and textContent
innerHTML
innerHTML is a property that allows you to get or set the HTML markup contained within an element. It can parse and render HTML tags, making it useful for dynamically updating the structure of a webpage.
Example
const element = document.getElementById('example');element.innerHTML = '<strong>Bold Text</strong>'; // This will render as bold text
Use cases
- Dynamically adding or updating HTML content
- Rendering HTML tags and elements
Security considerations
Using innerHTML can expose your application to Cross-Site Scripting (XSS) attacks if you insert untrusted content. Use textContent when the value is plain text. If users are intentionally allowed to author a limited HTML subset, process it with a maintained, allowlist-based HTML sanitizer before insertion and consider enforcing Trusted Types.
textContent
textContent is a property that allows you to get or set the text content of an element. It ignores any HTML tags and renders them as plain text, making it safer for inserting user-generated content.
Example
const element = document.getElementById('example');element.textContent = '<strong>Bold Text</strong>'; // This will render as plain text: <strong>Bold Text</strong>
Use cases
- Safely inserting user-generated content
- Inserting a string as literal text without parsing markup
Performance considerations
textContent avoids HTML parsing, but performance depends on the operation and document. Choose between the APIs for semantics and security first; profile a real bottleneck before making a performance claim.
Further reading
- MDN Web Docs: innerHTML
- MDN Web Docs: textContent
- Cross-Site Scripting (XSS)
- OWASP DOM based XSS Prevention Cheat Sheet