JAVASCRIPT
Update Text and HTML Content of DOM Elements
Learn to safely update an element's plain text content using `textContent` or render dynamic HTML with `innerHTML`, understanding the important security implications of each approach.
document.addEventListener('DOMContentLoaded', () => {
const textElement = document.getElementById('myParagraph');
const htmlElement = document.getElementById('myDiv');
if (!textElement || !htmlElement) {
console.error('One or more target elements not found.');
return;
}
// 1. Using textContent: Safe for plain text, prevents XSS
const newPlainText = 'This is new plain text. Special characters like <script>alert("XSS")</script> are escaped.';
textElement.textContent = newPlainText;
console.log('textContent updated:', textElement.textContent);
// Get text content (sanitized)
const currentText = textElement.textContent;
console.log('Current text content:', currentText);
// 2. Using innerHTML: Renders HTML, susceptible to XSS if input is untrusted
const newHtmlContent = '<b>This is bold HTML</b> and <i>this is italic</i>.';
htmlElement.innerHTML = newHtmlContent;
console.log('innerHTML updated:', htmlElement.innerHTML);
// Get HTML content
const currentHtml = htmlElement.innerHTML;
console.log('Current innerHTML:', currentHtml);
// !!! WARNING: Example of potential XSS with innerHTML if not sanitized !!!
const userSuppliedContent = "<img src='x' onerror='alert(\'You are hacked!\')'>";
// If you must use innerHTML with user input, sanitize it first.
// htmlElement.innerHTML = userSuppliedContent; // DO NOT DO THIS WITH UNSANITIZED USER INPUT!
});
/*
HTML structure for this example:
<p id="myParagraph">Original paragraph text.</p>
<div id="myDiv">Original div content.</div>
*/
How it works: This snippet illustrates the two primary ways to modify an element's content. `textContent` sets or retrieves the plain text content of an element, automatically escaping any HTML, making it safe from Cross-Site Scripting (XSS) attacks when dealing with user-supplied data. In contrast, `innerHTML` interprets and renders HTML strings, offering more flexibility but demanding careful sanitation of inputs to prevent XSS vulnerabilities when inserting untrusted content.