How can JavaScript be used to modify links for included content in PHP to ensure proper functionality?

When including content in PHP, links within that content may not work correctly due to the file paths being relative to the included file rather than the main file. To ensure proper functionality, JavaScript can be used to modify these links by dynamically updating their paths based on the main file's location.

<?php
// Include the content file
ob_start();
include 'content.php';
$content = ob_get_clean();

// Output the content with JavaScript link modification
echo $content;
?>

<script>
  // Get the base URL of the main file
  var baseUrl = window.location.href;

  // Select all links within the included content
  var links = document.querySelectorAll('a');

  // Loop through each link and update its href attribute
  links.forEach(function(link) {
    var oldHref = link.getAttribute('href');
    var newHref = baseUrl + oldHref;
    link.setAttribute('href', newHref);
  });
</script>