What are the potential security risks associated with using JavaScript to generate dynamic HTML code?

One potential security risk associated with using JavaScript to generate dynamic HTML code is Cross-Site Scripting (XSS) attacks. This occurs when an attacker injects malicious scripts into a web application, which can then be executed in the browsers of unsuspecting users. To prevent XSS attacks, it is crucial to properly sanitize and validate user input before dynamically generating HTML code.

<?php
// Sanitize and validate user input before using it to generate dynamic HTML code
$user_input = $_POST['user_input'];
$sanitized_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

// Generate dynamic HTML code using the sanitized input
echo "<div>" . $sanitized_input . "</div>";
?>