← Back to all snippets
JAVASCRIPT

Prevent XSS by HTML Escaping Output

Learn to prevent Cross-Site Scripting (XSS) attacks by properly escaping user-generated content before rendering it in HTML, safeguarding your web application.

function escapeHTML(str) {
  const div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
}

// Usage example:
const userInput = '<script>alert("You are hacked!")</script>';
const safeOutput = escapeHTML(userInput);

document.getElementById('output-area').innerHTML = `Safe output: ${safeOutput}`;
// This will render '&lt;script&gt;alert(&quot;You are hacked!&quot;)&lt;/script&gt;' as text,
// preventing the script from executing.
How it works: This JavaScript snippet demonstrates a simple yet effective way to prevent Cross-Site Scripting (XSS) vulnerabilities. By creating a temporary `div` element and appending the untrusted string as a text node, the browser automatically escapes all HTML special characters (like '<', '>', '&', '"', "'"). When `div.innerHTML` is retrieved, it returns the safely escaped string, which can then be rendered in the DOM without executing malicious scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs