Why are onclick functions not working on HTML elements created dynamically with PHP?

When HTML elements are created dynamically with PHP, the onclick functions may not work because the event listeners are not attached to the elements at the time of page load. To solve this issue, you can use event delegation by attaching the event listener to a parent element that is present when the page loads. This way, the event listener will still work for dynamically created elements.

<?php
// Example of creating a dynamic button with onclick function using event delegation

echo '<div id="parentElement"></div>';

echo '<script>';
echo 'document.getElementById("parentElement").addEventListener("click", function(event) {';
echo '  if(event.target && event.target.nodeName == "BUTTON") {';
echo '    alert("Button clicked!");';
echo '  }';
echo '});';
echo '</script>';

echo '<button>Click me</button>';
?>