How to make a function wait until element exists with JavaScript?

Spread the love

Sometimes, we want to make a function wait until element exists with JavaScript.

In this article, we’ll look at how to make a function wait until element exists with JavaScript.

How to make a function wait until element exists with JavaScript?

To make a function wait until element exists with JavaScript, we use the MutationObserver.

For instance, we write

const handleCanvas = (canvas) => {
  //...
};

const observer = new MutationObserver((mutations, me) => {
  const canvas = document.getElementById("my-canvas");
  if (canvas) {
    handleCanvas(canvas);
    me.disconnect();
    return;
  }
});

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

to call the MutationObserver constructor with a callback that’s called when there’re any changes in the DOM.

In it, we get the canvas element with getElementById.

If it exists, then we call the handleCanvas function and call disconnect to stop watching for DOM changes.

We call observer.observe to start watching for DOM changes on document.

We set childList and subtree to true to watch for nested DOM tree changes.

Conclusion

To make a function wait until element exists with JavaScript, we use the MutationObserver.

Leave a Reply

Your email address will not be published. Required fields are marked *