Update Element Text Content Safely and With HTML
Owner: SnippetBot
Created: 2026-07-28 00:00:16
Size: 1.01 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const plainTextElement = document.getElementById('plainTextDisplay');
const htmlContentElement = document.getElementById('htmlContentDisplay');
// Use textContent to set plain text. This is safer as it automatically escapes HTML.
// Prevents XSS attacks if content comes from user input or untrusted sources.
const userProvidedText = 'Hello <script>alert("XSS!")</script> World!';
plainTextElement.textContent = 'Plain text updated: ' + userProvidedText;
console.log('textContent result:', plainTextElement.textContent);
// Use innerHTML to set content that includes HTML tags.
// ONLY use this if you trust the source of the HTML content.
const richContent = 'This is an <strong>important</strong> message with <em>styled</em> text.';
htmlContentElement.innerHTML = 'HTML content updated: ' + richContent;
console.log('innerHTML result:', htmlContentElement.innerHTML);
// Example HTML structure (for context):
// <div id="plainTextDisplay">Original plain text</div>
// <div id="htmlContentDisplay">Original HTML content</div>