Setting Element Content: textContent vs innerHTML
You'll learn how to safely add content to DOM elements and understand critical security differences between methods.
When you create or select an element, you need a way to put content inside it. The DOM offers several properties for this: textContent, innerHTML, and innerText. Each behaves differently, and choosing the wrong one can create serious security vulnerabilities.
The Three Content Properties
textContent sets or retrieves all text inside an element. It treats everything as plain text—no HTML tags are parsed. If you assign "<strong>Hello</strong>" to textContent, those angle brackets appear literally on the page.
innerHTML parses content as HTML. When you assign "<strong>Hello</strong>" to innerHTML, the browser creates actual HTML elements. The text will appear bold.
innerText is similar to textContent but "aware" of CSS styling. It respects visibility and returns text as it appears to the user. For most cases, prefer textContent for better performance.
The XSS Danger
Think of innerHTML like a door to your house—convenient when you control what comes through, dangerous if a stranger has the key. Cross-Site Scripting (XSS) attacks happen when user-supplied data containing malicious code gets inserted via innerHTML.
// DANGEROUS - never do this with user input
element.innerHTML = userInput; // If userInput contains <script>...</script>, it executes!
// SAFE - treats everything as text
element.textContent = userInput; // Script tags appear as text, don't execute
Use textContent by default. Only use innerHTML when you're inserting trusted HTML that you control—never with user-generated content unless it's been properly sanitized.
Key Takeaway: Use textContent for plain text content to prevent XSS attacks; only use innerHTML with trusted HTML you control, never with unsanitized user input.