There are many different ways to solve this use case. You want to wait for an element to exist on the page and when it does, run a callback function. It seems simple enough, but what’s the easiest way?
By using some recursion and a setInterval
call, we can poll for an element using document.querySelector
and if it exists before the timeout value is reached, we return it by calling the callback
function with our element.
function waitForElement(selector, callback, timeout = 15000) { const start = Date.now(); let interval = setInterval(() => { const el = document.querySelector(selector); if (el) { clearInterval(interval); callback(el); } else if (Date.now() - start > timeout) { clearInterval(interval); callback(null); } }, 1000); }
You can achieve the same thing with a setTimeout
, you can even use a MutationObserver
to observe the element. In this instance, using an interval works for me.
You could shorten the “if” to:
if (el || Date.now() – start > timeout)
If the “querySelector” can’t find the element it will return “null”, making the “if” and “else if” the same as it’ll call the callback with an “el” of “null”.