Automatically update the text of a heading on the page with the display value of a selected choice of a specific facet

<?php
// Automatically updates the text in a specific <h1> heading tag on the page with the display value of the selected choice of a specific facet.
// Assumes the facet is a single-choice type facet (e.g. Dropdown or Radio).

add_action( 'wp_head', function() {
  ?>
  <script>
    document.addEventListener('facetwp-loaded', function() { // Runs after the refresh process, on each AJAX page load, and on the initial page load.   
      let selected = FWP.facets['pubtype']; // Replace "pubtype" with the name of your facet
      if ( selected.length ) { // If any choice in this facet is selected

        // Find the <h1> tag with class "page-title"
        var h1WithTitle = document.querySelector('h1.page-title');

        // Update the text content of the <h1 class="page-title"> tag
        if ( h1WithTitle ) {
          h1WithTitle.textContent = selected;
        }  
      }
    });     
  </script>
  <?php
}, 100 );