JAVASCRIPT
Update Element Text and HTML Content Safely
Understand the difference between `textContent` and `innerHTML` for updating element content, and learn when to use each for security and formatting purposes.
const contentDiv = document.getElementById('content-area');
// Safely set plain text content
// Any HTML tags in the string will be rendered as literal text
const safeText = 'Hello, <strong>world</strong>! This is <script>alert("XSS")</script> safe.';
contentDiv.textContent = safeText;
console.log('Text content:', contentDiv.textContent);
// Set HTML content (use with caution, can introduce XSS if input is not sanitized)
// HTML tags in the string will be parsed and rendered by the browser
const htmlContent = '<em>Emphasis</em> and <a href="#">a link</a>.';
contentDiv.innerHTML = htmlContent;
console.log('HTML content:', contentDiv.innerHTML);
// Get plain text content
const currentText = contentDiv.textContent;
console.log('Current plain text:', currentText);
// Get raw HTML content
const currentHtml = contentDiv.innerHTML;
console.log('Current raw HTML:', currentHtml);
How it works: This snippet highlights two crucial properties for modifying an element's content: `textContent` and `innerHTML`. `textContent` sets or gets the plain text content of an element, stripping out any HTML tags and rendering them as literal text. This makes it the safest choice for displaying user-generated input, preventing Cross-Site Scripting (XSS) attacks. In contrast, `innerHTML` sets or gets the raw HTML content, parsing any HTML tags within the string. While powerful for dynamic HTML generation, using `innerHTML` with unsanitized user input is a major security risk as it can execute malicious scripts.