Over a million developers have joined DZone.

Waiting for an Element to be Created [Code Snippet]

DZone's Guide to

Waiting for an Element to be Created [Code Snippet]

A small function using MutationObserver to identify when an element is added to the DOM.

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

In my trials and tribulations to detect when a field has been auto-filled, I need to create a shim for monitorEvents so that I can see the event lifecycle 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(id) {
  return new Promise(function(resolve, reject) {
    var elementId = id.substr(1);
    var element = document.getElementById(elementId);

    if(element) {

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        var nodes = Array.from(mutation.addedNodes);
        nodes.forEach(function(node) {
          if(node.id == elementId) {

    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 lifecycle 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) {

Technically I still haven’t solved the issue of “how can you tell when Firefox has auto completed fields” but I have the tools at my disposal.

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

javascript ,monitor ,elements ,web dev

Published at DZone with permission of Paul Kinlan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}