raingart Author




Sorry for the late reply. Sites (openuserjs.org) don't notify me of new posts if I'm logged in via github


here is an implementation example on MutationObserver
MutationObserver checks after every change. In some cases, setInterval is more efficient due to the cost of fewer resources.

    waitElement('body')
      .then(el => {
        console.log('el:', el);
      });

function waitElement(selector, container) {
  if (container && !(container instanceof HTMLElement)) return console.error('wait > container not HTMLElement:', container);

  return new Promise(resolve => {
    if (element = (container || document.body || document).querySelector(selector)) return resolve(element);

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

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

you can use asynchronous calls
await Promise.resolve(document.body.querySelector(selector))

or you can use Promise. But alas, it does not return the element itself. It is only suitable for waiting for the html element

function waitElement(selector = required(), container) {
   if (typeof selector !== 'string') return console.error('wait > selector:', typeof selector);
   if (container && !(container instanceof HTMLElement)) return console.error('wait > container not HTMLElement:', container);
   // console.debug('waitElement:', selector);

   return Promise.resolve((container || document.body).querySelector(selector));
}