Show/hide button based on text (logic) on page

Hello

I have a “Cart” page (that lists products in a Cart) that has a “Clear cart” button. I want to show this button only when there are items in the Cart. The easiest way I found was simply to verify if “Cart is empty” text is present in the page.
So the basic code would look like this:

      // Select the button element
      var button = document.querySelector('button[label="Clear cart"]');

      // Check if the button element and the target text exist
      if (button && document.body.textContent.includes('Cart is empty')) {
        // Hide the button
        button.style.display = 'none';
      }

After page is loaded, if I run the code above in Google Chrome inspector it works as expected. If I add this code to “Custom Code” of Softr it doesn´t work.

So I tried again, this time using setInterval()

    // Wait for the elements to appear on the page
    var intervalId = setInterval(function() {
      // Select the button element
      var button = document.querySelector('button[label="Clear cart"]');

      // Check if the button element and the target text exist
      if (button && document.body.textContent.includes('Cart is empty')) {
        // Hide the button
        button.style.display = 'none';
        
        // Clear the interval once the button is hidden
        clearInterval(intervalId);
      }
    }, 100); // Check every 100 milliseconds

This time it worked inside “Custom Code”
but…
When there is a item on Cart and the text “Cart is empty” is not shown in the page anymore, button “Clear cart” does not show…

Any suggestions?