How to wait until an DOM element exists in JavaScript? Solutions

Usually, when working with web pages, you may encounter a situation where you have to wait until a DOM element exists in JavaScript.

And also for a specific part of the page to show up before you can do something with it.

It can happen when the content is generated dynamically or when you’re using external libraries that modify the page.

In this article, we’ll guide you through using JavaScript to patiently wait until a particular element exists on the page before you can proceed with any actions.

How to check and wait until an DOM if element is exists in JavaScript?

To wait until a specific element exists on a webpage using JavaScript, you can use something called the MutationObserver API.

This lets you keep an eye on the document.body object and all its child elements for any changes.

The use of DOMNodeInserted and other DOM mutation events is being deprecated due to their negative impact on performance.

Instead, it is recommended to use more efficient method called MutationObserver to monitor changes in the DOM.

However, it’s important to note that MutationObserver is only supported in newer browsers. In cases where you’re working with older browsers, you can still rely on the fallback option of using DOMNodeInserted.

Solution 1: Use MutationObserver

We have a custom function called “waitForElementToExist” that we’ve created.

Inside this function, we use a timer (setTimeout) to wait for 3 seconds before adding an element with the ID “box” to the web page.

Here’s the complete code for script.js:

function waitForElementToExist(selector) {
  return new Promise((resolve) => {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (!mutation.addedNodes) return;
        for (let i = 0; i < mutation.addedNodes.length; i++) {
          let node = mutation.addedNodes[i];
          if (node.matches && node.matches(selector)) {
            observer.disconnect();
            resolve(node);
          }
        }
      });
    });
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: false,
    });
  });
}

// Add an element with the id of 'box' to the DOM after 3 seconds
setTimeout(() => {
  let box = document.createElement('div');
  box.id = 'box';
  document.body.appendChild(box);
}, 3000);

// Wait for the element with the id of 'box' to exist and log a message to the console
waitForElementToExist('#box').then((element) => {
  console.log('The element exists', element);
});

After the 3-second delay, we call the waitForElementToExist function and provide it with the information about the element we’re waiting for, which is identified by the selector “#box.”

Once the “box” element is successfully added to the page, the function resolves and prints a message to the console.

If you run this code in your browser’s developer console, you should see a message logged after 3 seconds that says “The element exists [object HTMLDivElement]”.

Output:

The element exists
<div id="box"></div>

Here’s the code for HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box">Itsourcecode</div>

    <script src="src/script.js"></script>
 
  </body>
</html>

Here’s another way in which you can use to wait until a DOM element exists in JavaScript using MutationObserver. It is most likely the same as the previous one.

However, we modify this code, and there are some changes, and the code is much shorter than the code above.

Here’s the example code for script.js

function waitForElementToExist(selector) {
  return new Promise(resolve => {
    if (document.querySelector(selector)) {
      return resolve(document.querySelector(selector));
    }

    const observer = new MutationObserver(() => {
      if (document.querySelector(selector)) {
        resolve(document.querySelector(selector));
        observer.disconnect();
      }
    });

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

// use this function

waitForElementToExist('#box').then(element => {
  console.log('The element is exists', element);
});

Console Output:

The element exists
<div id="box"></div>

Web view:

Itsourcecode

You can also use this function in your code:

async function doWork() {
  const element = await waitForElementToExist('#box');

  console.log('Element:', element);
}

doWork();

When you’re working with Promises in JavaScript, you can use the await keyword to pause your code and wait for the Promise to finish before moving on.

And the console output would be:

Element:
<div id="box"></div>

Here’s the code for HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box">Itsourcecode</div>

    <script src="src/script.js"></script>
 
  </body>
</html>

Solution 2: Use the setInterval() method to wait for an element to exist

The setInterval() method is like a handy tool that allows you to set up a recurring task. You provide it with a function that you want to be executed, and you can also specify the time delay in milliseconds.

In the example given, the provided function will be called every 100 milliseconds. However, if you need a different delay, you can easily adjust it as per your needs.

Here’s the example code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="box">Itsourcecode</div>

    <script src="src/script.js"></script>
 
  </body>
</html>

Here’s the example code of script.js

function waitForElementToExist(selector, callback) {
  const intervalID = setInterval(() => {
    if (document.querySelector(selector)) {
      console.log('The element exists');

      clearInterval(intervalID);

      callback(document.querySelector(selector));
    }
  }, 100);
}

waitForElementToExist('#box', function doWork(element) {
  console.log('Element:', element);
});

Output:

The element exists
Element:
<div id="box"></div>

Conclusion

In conclusion, this article discussed two ways to handle the situation where you need to wait until a DOM or a specific element to exist in JavaScript.

The first method suggests using the MutationObserver API, which is recommended for newer browsers.

The second method proposes using the setInterval() function to continuously check for the element’s existence. Both approaches provide effective solutions for this task in JavaScript.

Both of these solutions provide practical ways to address situations where you need to wait for a specific DOM element to be available before proceeding with further actions in JavaScript.

It’s important to choose the method that best fits your requirements in terms of browser compatibility and personal coding preferences.

We are hoping that this article provides you with enough information that helps you understand the JavaScript wait until element exists. 

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment