Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I securely handle sensitive data in client-side JavaScript to prevent XSS attacks?
Asked on Jan 05, 2026
Answer
To securely handle sensitive data in client-side JavaScript and prevent XSS attacks, it's important to sanitize and encode any data that will be inserted into the DOM. Here's a simple example of how to safely insert user input into a webpage.
<!-- BEGIN COPY / PASTE -->
function sanitizeInput(input) {
const div = document.createElement('div');
div.textContent = input;
return div.innerHTML;
}
const userInput = "<script>alert('XSS');</script>";
const safeInput = sanitizeInput(userInput);
const outputElement = document.getElementById('output');
outputElement.innerHTML = safeInput;
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This example uses a DOM element to automatically escape HTML special characters, preventing script execution.
- Always use "textContent" or "innerText" for setting text, and avoid "innerHTML" unless the content is sanitized.
- Never trust user input; always sanitize and validate it before using it in your application.
- Consider using libraries like DOMPurify for more comprehensive sanitization needs.
Recommended Links:
