What are some best practices for dynamically assigning content to HTML elements using PHP and JavaScript?

When dynamically assigning content to HTML elements using PHP and JavaScript, it is important to ensure that the content is properly escaped to prevent cross-site scripting attacks. One best practice is to use PHP to generate the dynamic content and then pass it to JavaScript for insertion into the HTML elements. This helps separate the server-side logic from the client-side presentation, making the code easier to maintain and more secure.

<?php
// PHP code to generate dynamic content
$dynamicContent = "Hello, world!";
?>

<script>
// JavaScript code to insert dynamic content into HTML element
var dynamicContent = "<?php echo htmlspecialchars($dynamicContent); ?>";
document.getElementById("myElement").innerHTML = dynamicContent;
</script>