Home > Back-end >  Waiting for element to appear before inserting javascript element not working
Waiting for element to appear before inserting javascript element not working

Time:11-09

I'm trying to add a button to the wordpress elementor mini cart when it's empty. To do this i thought i'd use a promise to wait for the element to load then insert some adjacent html code to display the button.

Both parts appear to work separately the returning of a promise and then inserting the element. However when they work together no element appears? Any ideas on how to debug this? What to look out for. How can i monitor the order of each thing firing to make sure it's happening in the right order?

Here's the code I have below: It's a snippet for wordpress.

<script>
    const checkElement = async selector => {
        while ( document.querySelector(selector) === null) {
            await new Promise( resolve =>  requestAnimationFrame(resolve) )
        }
        return document.querySelector(selector); 
    };

    checkElement('.woocommerce-mini-cart__empty-message').then((selector) => {
        
        var message = `
            <div style="margin-top:2rem" >
                <a href="/toilets" >
                    <span elementor-button-content-wrapper">
                        <span >View our products</span>
                    </span>
                </a>
            </div>`;
        selector.insertAdjacentHTML('afterend', message);
        console.log(selector);
    });

</script>
<?php } );

The page in question is https://staging-woowoowaterlesstoilets.kinsta.cloud/ if you click on the basket when there is nothing there, there should appear a button. It was working before but after updating some plugins and wordpress it's stopped working.

CodePudding user response:

this would be simpler

const liveSelector = document.getElementsByClassName('woocommerce-mini-cart__empty-message');
let tId = setInterval(function() {
  if (liveSelector.length > 0) {
    clearInterval(tId)
    var message = `
            <div style="margin-top:2rem" >
                <a href="/toilets" >
                    <span elementor-button-content-wrapper">
                        <span >View our products</span>
                    </span>
                </a>
            </div>`;
    liveSelector[0].insertAdjacentHTML('afterend', message);
    console.log("done");
  }
}, 500);
  • Related