Skip to content

Instantly share code, notes, and snippets.

@matthewpwatkins
Created May 17, 2021 21:05
Show Gist options
  • Save matthewpwatkins/bd40626d18876fc25216929a1d27d5d7 to your computer and use it in GitHub Desktop.
Save matthewpwatkins/bd40626d18876fc25216929a1d27d5d7 to your computer and use it in GitHub Desktop.
JS Wait for element to exist

If you don't want to use a mutation observer and you just want to periodically poll to find an element, here's how to do that with async/await:

const elements = await waitForElementsToExist('div.my-class');

function waitForElementsToExist(selector, interval = 100, retriesLeft = 100) {
    return new Promise((accept, reject) => {
        setElementsTimeout(selector, interval, retriesLeft, accept, reject);
    });
}

function setElementsTimeout(selector, interval, retriesLeft, accept, reject) {
    retriesLeft--;
    const element = document.querySelectorAll(selector);
    if (element) {
        accept(element);
    } else {
        if (retriesLeft > 0) {
            setTimeout(() => {
                setElementTimeout(selector, interval, retriesLeft, accept, reject);
            }, interval);
        } else {
            reject(`Ran out of patience waiting for ${selector}`);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment