JAVASCRIPT

Safely Display User Input with TextContent for XSS Prevention

Prevent Cross-Site Scripting (XSS) by securely displaying user-generated plain text content in the DOM using textContent instead of innerHTML, ensuring characters are safely encoded.

const userInput = "<script>alert('XSS!');</script>User provided text.";
const outputElement = document.getElementById('user-output');

// CORRECT & SECURE: Use textContent for plain text
outputElement.textContent = userInput;

// INCORRECT & INSECURE: Do NOT use innerHTML for untrusted input
// outputElement.innerHTML = userInput; // DANGER! Leads to XSS
How it works: This snippet demonstrates the fundamental way to prevent XSS when displaying user-generated plain text. By assigning user input to `textContent`, the browser automatically encodes any HTML special characters, rendering them harmless text instead of executable code. This is crucial for securely displaying data from untrusted sources, ensuring that malicious scripts embedded in the input are not executed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs