When displaying fetched data, especially user-generated content, proper sanitization is crucial to prevent XSS attacks. Best practices include: 1) Never using innerHTML with unsanitized content, 2) Using textContent or createElement for safe DOM manipulation, 3) Implementing proper HTML sanitization libraries like DOMPurify when HTML content is necessary, 4) Validating and escaping all user-generated content before display. A safer implementation would be:
function displayUserComment(comment) {
const commentDiv = document.createElement('div');
commentDiv.textContent = comment.content; // Safe from XSS
// Or if HTML is needed:
// commentDiv.innerHTML = DOMPurify.sanitize(comment.content);
document.getElementById('comments').appendChild(commentDiv);
}