← Back to all snippets
JAVASCRIPT

Updating Element Content with `innerHTML` (and Security Caution)

Learn how to dynamically change the HTML content of a DOM element using the `innerHTML` property, while understanding and mitigating potential Cross-Site Scripting (XSS) risks.

function updateElementHTML(elementId, newHTMLContent, sanitize = true) {
  const targetElement = document.getElementById(elementId);
  if (!targetElement) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  if (sanitize) {
    // A simple, *incomplete* example of sanitization.
    // For production, use a dedicated library like DOMPurify.
    const tempDiv = document.createElement('div');
    tempDiv.innerText = newHTMLContent; // Use innerText to escape HTML
    targetElement.innerHTML = tempDiv.innerHTML;
    console.warn("Content was sanitized. For robust protection, use a library like DOMPurify, especially with user-generated content.");
  } else {
    targetElement.innerHTML = newHTMLContent;
    console.warn("WARNING: Using innerHTML without sanitization can lead to XSS vulnerabilities if 'newHTMLContent' contains untrusted user input.");
  }
}

// Usage example:
// <div id="contentArea">Original content</div>
// updateElementHTML('contentArea', '<h2>New Title</h2><p>Some paragraph.</p>');
// updateElementHTML('contentArea', '<script>alert("XSS attempt!");</script>', false); // DANGEROUS!
// updateElementHTML('contentArea', '<script>alert("XSS attempt!");</script>', true); // Safer (will render as text)
How it works: This snippet demonstrates how to update the entire HTML content of an element using the `innerHTML` property. While powerful for injecting rich content, it carries a significant security risk (Cross-Site Scripting - XSS) if the `newHTMLContent` comes from untrusted user input. The function includes a `sanitize` option to illustrate a basic (but insufficient for production) sanitization approach using `innerText` to escape HTML tags. For real-world applications, it's crucial to use robust sanitization libraries like DOMPurify when dealing with user-generated content and `innerHTML`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs