javascript - How to wait until an element exists? - Stack Overflow

PHOTO EMBED

Thu Dec 01 2022 15:14:54 GMT+0000 (Coordinated Universal Time)

Saved by @AZbrahim

//1
function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}


//2
waitForElm('.some-class').then((elm) => {
    console.log('Element is ready');
    console.log(elm.textContent);
});

//3
const elm = await waitForElm('.some-class');
content_copyCOPY

https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists