Waiting for an element to be created

In my trials and tribulations to detect when a field has been autofilled, I need to create a shim for monitorEvents so that I can see the event life-cycle of that element and ultimately try to debug it.

One thing that I found is that monitorEvents requires an element but for what I am doing I know that there will be an element with an id at some point but I don't know when it will be created.

I quickly knocked out a small function called waitForElement that uses the MutationObserver to look for when an element with a given id is added to the DOM. When that element has been detected it will resolve the promise and return the element.

The code is as follows:

function waitForElement(selector) {
  return new Promise(function(resolve, reject) {
    var element = document.querySelector(selector);

    if(element) {
      resolve(element);
      return;
    }

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        var nodes = Array.from(mutation.addedNodes);
        for(var node of nodes) {
          if(node.matches && node.matches(selector)) {
            observer.disconnect();
            resolve(node);
            return;
          }
        };
      });
    });

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

Here is the gist if that is your bag.

It is pretty simple to use this simple API.

waitForElement("#test").then(function(element) {
    console.log("Element Added", element);
});

Now combining in the monitorEvents function from my previous post, I can now set a breakpoint early in the life-cycle of a page (because scripts in the head block) and set up a waitForElement call that can now start logging all the events that are firing on that element.

waitForElement("#test").then(function(element) {
    monitorEvents(element);
});

Technically I still haven't solved the issue of "how can you tell when Firefox has autocompleted fields" but I have the tools at my disposal.

Pretty chuffed.

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)