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 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment