Add a counter text to Listing Builder items

<?php
// Adds a div with class "item-number" to each Listing Builder listing item, 
// with a counter text that counts the builder items in the post: e.g. "# of total", e.g. "1 of 20".

add_action( 'facetwp_scripts', function() {
  ?>

  <script>

    document.addEventListener('facetwp-loaded', function() {

      // Select all parent elements with class .fwpl-col
      const parentElements = document.querySelectorAll('.fwpl-col');

      // Loop through each parent element
      parentElements.forEach(parentElement => {

        // Select direct child elements with class .fwpl-item
        const childElements = Array.from(parentElement.children).filter(child => child.classList.contains('fwpl-item'));

        // Set the total number of items
        const totalItems = childElements.length;

        // Add a div with the text to each child element
        childElements.forEach((childElement, index) => {
          // Create a new div element
          const textDiv = document.createElement('div');
          textDiv.classList.add('item-number');
          textDiv.textContent = (index + 1) + ' of ' + totalItems;

          // Append the text div to the child element
          childElement.appendChild(textDiv);
        });
      });

    });

  </script>

  <?php
}, 100 );