How to wait until an element exists?
Asked Answered
N

30

517

I'm working on an Extension in Chrome, and I'm wondering: what's the best way to find out when an element comes into existence? Using plain javascript, with an interval that checks until an element exists, or does jQuery have some easy way to do this?

Neddra answered 2/4, 2011 at 18:32 Comment(9)
Looks like every single option here today (including from comments) is either outdated or incomplete. They don't consider @hughsk's awesome input fully, the compatibility argument. Meanwhile I'd recommend simply using Brandon's update on Ryan's answer for general simplicity and less risk of overhead, I suppose.Sitsang
MutationObserver > DOM Mutation Events > setTimeout.Neddra
Not from where I stand. setTimeout is compatible, simple to implement, simple to maintain, and has negligible overhead.Sitsang
setTimeout + jQuery is less than ideal in my opinion for two reasons: 1.) jQuery bloat 2.) you're needlessly manually querying the DOM for elements, events beat that speed-wise easily, 3.) it will always be slower than any native implementation. If you need to do anything based on the presence of an element reasonably quickly, especially if seamless user experience is your goal, it is inferior.Neddra
That said, that is why I dislike it. The other solutions are more robust, immediate, less likely to break or suffer from bugs, and most importantly more detailed as to what changes occurred. If you are working in a situation where you have complete control or only need DOM change updates for simple, uncomplicated elements hierarchies it's probably great.Neddra
(...I can't count)Neddra
There are 3 kinds of people: those who can count and those who can't. ;PSitsang
@Neddra I think you could consider mark my answer as accepted, because the currently accepted answer is fully useless, specially for beginners, is just a bad copy paste of the documentation. I spent many hours understing how it works and how to make a simple working example. And if you read the comments of accepted answer they think MutationObserver is hard and complex when it isn´t. My answer can help future visitors in their own context. Regards.Brace
@Brace The currently accepted answer of hugh's is much simpler than yours and doesn't depend on jQuery.Aslant
F
234

DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (!mutation.addedNodes) return

    for (let i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      let node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()
Freida answered 24/5, 2013 at 2:7 Comment(13)
I've always found MutationObserver api a bit complex so I've built a library, arrive.js, to provide a simpler api to listen for elements creation/removal.Timeworn
I recommend using @UzairFarooq excellent library github.com/uzairfarooq/arriveScorpaenid
@Freida : How I can do it only for a particular <div>element?Monocot
As noted, MutationObservers don't work in IE10 or below. I believe part of Web Components has made a polyfill for IE9 support here.Gottwald
Two things to note: (1) It would be better to do if (mutation.addedNodes.length) since if (mutation.addedNodes) would still return true even if it's an empty array. (2) You can't do mutation.addedNodes.forEach() because addedNodes is a nodeList and you can't iterate through a nodeList with forEach. For a solution to this, see toddmotto.com/ditch-the-array-foreach-call-nodelist-hackLuminescence
Just encapsulated answer to jQuery plugin available via Bower. github.com/janmisek/jquery.elementReadyCushitic
@UzairFarooq I tried your library tool Arrive and it is not working at all, I am using Chrome, I wisely followed your github instruction and tried to debug it several times, but it does not work.Sapir
@Katcha can you provide me jsfiddle of the issue?Timeworn
Can you give an example of how one would use this? Not sure where to put my jquery selector or code I want executed when DOM element exists.Knack
This is harder than it looks, does anyone have a working algo using MutationObserver in 2019?Penney
@Knack I made an answer with easy example. Check it. https://mcmap.net/q/73794/-how-to-wait-until-an-element-existsBrace
@TalkNerdyToMe this answer doesn't use mutation events, it uses the mutationObserver interface, so it is still very relevant.Neoclassic
@MikeKormendy You're correct; I have deleted my comment.Marya
H
636

Here is a simple solution using the MutationObserver api.

  1. No jQuery
  2. No Timer
  3. No third party libraries
  4. Promise based and works well with async/await

I have used it in several projects.

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

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

        // If you get "parameter 1 is not of type 'Node'" error, see https://mcmap.net/q/75048/-39-observe-39-on-39-mutationobserver-39-parameter-1-is-not-of-type-39-node-39
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

To use it:

waitForElm('.some-class').then((elm) => {
    console.log('Element is ready');
    console.log(elm.textContent);
});

Or with async/await:

const elm = await waitForElm('.some-class');
Halette answered 29/4, 2020 at 21:23 Comment(19)
This is neat! The cool part about it is that you could use it with async / await too. You might also be able squeeze more performance out of it by doing mutations.addedNodes.find(node => node.matchesSelector("..."))Neddra
@Neddra Good point! Checking just the nodes in the mutations is more performant than doing document.querySelector.Halette
This is awesome, thanks. But what is the purpose of that mutations param inside the observer constant?Jerz
@RalphDavidAbernathy, you are right, the mutations param is not used in the code and can be safely deleted. It has a lot of useful information on what is mutated. I put it there just in case you need to access it.Halette
Finally! I tried everything in the book, but couldn't fetch the element by class. I even ran the function on window.load but no help. This did it! Thanks @YongWangReserpine
This function is checking the item coming in DOM for first time, how to check if item coming more times, so every time it should run,Amuse
This appears to override any other code that monitors the targeted element(s) for events. I have a page where I'm trying to watch for changes to an input based on other code that I do not control (within my own user script, monitoring a form from a website, conditionally applying formatting). The above code causes the page's own JS to cease functioning for the targeted element(s). Is there any way to monitor an element, without clobbering any existing event watchers? Perhaps similar to jQuery's noConflict()?Huffish
I'm passing as a parameter the value ('#'+num), where num is '123456' as an example. And having an error 'selector is not valid'(((. Using getElementById() or jquery fixes this and everything works... How to deal with this?Nematode
rules.sonarsource.com/javascript/RSPEC-3801 - seems having the return there is a major code smell - removed and added various logs to see if that's an issue (if I'm just re-adding the observer in an annoying way) - but it turns out not. So can safely remove the return statement in the if there...Home
@Julix, the if-return statement is an optimization for the case that the element if already present when you call this function. The promise will be resolved directly without having to mess with MutationObserverHalette
Good point, Yong. - Would you then add an empty return at the end or how would you comply with 'Functions should use "return" consistently'?Home
The return here is just used to stop executing the rest codes. In that case, you can remove the return, and wrap the remaining code in a else blockHalette
This differs from the oldschool timeout+querySelector approach. For example, if you have a <div> on the page, and you wait for the selector ".foo", then later you div.addClass("foo"). The selector now resolves, but the waitFor utility doesn't find it.Latimore
How do repeated calls to document.querySelector(selector) perform? What I mean by that: would it be useful to cache the value before the if, so that the then-branch can also use it?Emotive
@EiríkrÚtlendi Did you find a way to simulate the noConflict() functionality?Stirling
@enissay, unfortunately, no. We gave up on the idea. It was only a nice-to-have for us anyway, flagging a particular value if out of expected range. While more error-prone, we've just asked our humans to keep their eyes peeled. :)Huffish
Wouldn't it be better to swap around calls to resolve(...) and observer.disconnect()? What if the lambda passed into .then() causes more mutations?Emotive
You, my friend, are a savior. I've been looking for ways to solve this problem of mine for days and this method of yours saved this pain in my as*. Thank you.Mccrae
Love this, this is the second time this has saved my day.Hindsight
F
234

DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

let observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (!mutation.addedNodes) return

    for (let i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      let node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()
Freida answered 24/5, 2013 at 2:7 Comment(13)
I've always found MutationObserver api a bit complex so I've built a library, arrive.js, to provide a simpler api to listen for elements creation/removal.Timeworn
I recommend using @UzairFarooq excellent library github.com/uzairfarooq/arriveScorpaenid
@Freida : How I can do it only for a particular <div>element?Monocot
As noted, MutationObservers don't work in IE10 or below. I believe part of Web Components has made a polyfill for IE9 support here.Gottwald
Two things to note: (1) It would be better to do if (mutation.addedNodes.length) since if (mutation.addedNodes) would still return true even if it's an empty array. (2) You can't do mutation.addedNodes.forEach() because addedNodes is a nodeList and you can't iterate through a nodeList with forEach. For a solution to this, see toddmotto.com/ditch-the-array-foreach-call-nodelist-hackLuminescence
Just encapsulated answer to jQuery plugin available via Bower. github.com/janmisek/jquery.elementReadyCushitic
@UzairFarooq I tried your library tool Arrive and it is not working at all, I am using Chrome, I wisely followed your github instruction and tried to debug it several times, but it does not work.Sapir
@Katcha can you provide me jsfiddle of the issue?Timeworn
Can you give an example of how one would use this? Not sure where to put my jquery selector or code I want executed when DOM element exists.Knack
This is harder than it looks, does anyone have a working algo using MutationObserver in 2019?Penney
@Knack I made an answer with easy example. Check it. https://mcmap.net/q/73794/-how-to-wait-until-an-element-existsBrace
@TalkNerdyToMe this answer doesn't use mutation events, it uses the mutationObserver interface, so it is still very relevant.Neoclassic
@MikeKormendy You're correct; I have deleted my comment.Marya
S
135

Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).

// Call the below function
waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);

function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
  var startTimeInMs = Date.now();
  (function loopSearch() {
    if (document.querySelector(selector) != null) {
      callback();
      return;
    }
    else {
      setTimeout(function () {
        if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
          return;
        loopSearch();
      }, checkFrequencyInMs);
    }
  })();
}

This call will look for the HTML tag whose id="div1" every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.

Parameters:

  1. selector: String : This function looks for the element ${selector}.
  2. callback: Function : This is a function that will be called if the element is found.
  3. checkFrequencyInMs: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.
  4. timeoutInMs : Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.

NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Subtile answered 20/4, 2015 at 17:6 Comment(10)
Nice! Can you write this so that any selector can be accepted?Neddra
I doubt I can do it.. But please have a look at this post to get the getElementByXpath: #10596917Subtile
What about querySelector? developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorNeddra
Can you write it to use mutation observer instead?Penney
or could you rewrite this one to use a promise?Penney
You need to add timeout so it will not be an endless loop if the element was not found.Useful
@GravityAPI : I added the optional timeout to avoid enless loops.Subtile
@Penney : hughsk provided an example with the mutation observer, right ? As for a Promise, I will rewrite a new answer with it in the next couple of weeks. Sorry for the long long delay !!Subtile
This works in Chrome 2021! I tried 50 different ways to wait for an iFrame url to load in Chrome - nothing worked because I've been told Chrome initiates a blank webpage temporarily whenever the href is changed in an iFrame, so the load functions never fired since it was detecting the blank page already loaded. With this function I can at least wait for the iFrames parent to load. Just need to change the function from "if (document.querySelector(selector) != null) {" to "if (document.getElementById("myFrameIDname").contentDocument.querySelector(selector) != null) {"Dominoes
Maybe this was once a good solution, but seems overkill now if you can just observe the DOM.Saar
C
121

I was having this same problem, so I went ahead and wrote a plugin for it.

$(selector).waitUntilExists(function);

Code:

;(function ($, window) {

var intervals = {};
var removeListener = function(selector) {

    if (intervals[selector]) {

        window.clearInterval(intervals[selector]);
        intervals[selector] = null;
    }
};
var found = 'waitUntilExists.found';

/**
 * @function
 * @property {object} jQuery plugin which runs handler function once specified
 *           element is inserted into the DOM
 * @param {function|string} handler 
 *            A function to execute at the time when the element is inserted or 
 *            string "remove" to remove the listener from the given selector
 * @param {bool} shouldRunHandlerOnce 
 *            Optional: if true, handler is unbound after its first invocation
 * @example jQuery(selector).waitUntilExists(function);
 */

$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {

    var selector = this.selector;
    var $this = $(selector);
    var $elements = $this.not(function() { return $(this).data(found); });

    if (handler === 'remove') {

        // Hijack and remove interval immediately if the code requests
        removeListener(selector);
    }
    else {

        // Run the handler on all found elements and mark as found
        $elements.each(handler).data(found, true);

        if (shouldRunHandlerOnce && $this.length) {

            // Element was found, implying the handler already ran for all 
            // matched elements
            removeListener(selector);
        }
        else if (!isChild) {

            // If this is a recurring search or if the target has not yet been 
            // found, create an interval to continue searching for the target
            intervals[selector] = window.setInterval(function () {

                $this.waitUntilExists(handler, shouldRunHandlerOnce, true);
            }, 500);
        }
    }

    return $this;
};

}(jQuery, window));
Coxcombry answered 4/12, 2012 at 18:4 Comment(11)
Thank you for the plugin. I forked and improved it a bit. Feel free to take whatever you want from my update. I have a few more improvements planned, still: updated pluginPardoes
would be nice without jquery dep too... ;)Mundford
maybe you should mention how it works: it works by asking every 500 ms if the element exists (using a window.setInterval). I don't know if the MutationObserver answer works by polling as well...Nutritionist
It does not work properly if the element is already on the page. Here is the proper version of this function: gist.github.com/PizzaBrandon/5709010Workmanlike
Hey @RolandSoós thanks for the help! Any idea on how this can be used with a class selector with multiple classes possible being selected? $($('.selector')[0]).waitUntilExists(function) will not work at the moment, which is my issue. Any ideas or possible fixes? Thanks again!Demark
@Demark think that through... This function checks if an element for that select exists and notify you if it does. If an element is not the but others are there, this won't know that you are waiting for an element on an index...Workmanlike
Can you please explain what is the use of ; in the beginning of the function ( ;(function ($, window) { ) ?Sure
Yeah, I'd be interested in that too. I thought it had something to do with bad (i.e. non-closed) line-endings, but wasn't sure how that would come about.So I googled it: "It allows you to safely concatenate several JS files into one, to serve it quicker as one HTTP request." https://mcmap.net/q/75050/-what-does-the-leading-semicolon-in-javascript-libraries-doHome
Used to work for me, but does not seem to work anymore in Chrome 66.0.3359.117Knack
@Sure the ; is nowadays used to close the last line of the previous script if that script doesn't have ; at the end, it's a measure for paranoidsLowtension
@Knack That's the problem with relying on these self-made plugins. The maintenance is atrocious.Peremptory
S
53

I used this approach to wait for an element to appear so I can execute the other functions after that.

Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID appears or finished loading, we can use,

var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms
Stentorian answered 19/11, 2015 at 7:10 Comment(0)
I
30

Update

Below there is an updated version that works with promises. It also "stops" if a specific number of tries is reached.

function _waitForElement(selector, delay = 50, tries = 100) {
    const element = document.querySelector(selector);

    if (!window[`__${selector}`]) {
      window[`__${selector}`] = 0;
      window[`__${selector}__delay`] = delay;
      window[`__${selector}__tries`] = tries;
    }

    function _search() {
      return new Promise((resolve) => {
        window[`__${selector}`]++;
        setTimeout(resolve, window[`__${selector}__delay`]);
      });
    }

    if (element === null) {
      if (window[`__${selector}`] >= window[`__${selector}__tries`]) {
        window[`__${selector}`] = 0;
        return Promise.resolve(null);
      }

      return _search().then(() => _waitForElement(selector));
    } else {
      return Promise.resolve(element);
    }
  }

Usage is very simple, to use it with await just make sure you're within an async function:

const start = (async () => {
  const $el = await _waitForElement(`.my-selector`);
  console.log($el);
})();

Outdated version

Simply add the selector you want. Once the element is found you can have access to in the callback function.

const waitUntilElementExists = (selector, callback) => {
const el = document.querySelector(selector);

if (el){
    return callback(el);
}

setTimeout(() => waitUntilElementExists(selector, callback), 500);
}

waitUntilElementExists('.wait-for-me', (el) => console.log(el));
Interstate answered 31/5, 2019 at 17:8 Comment(7)
PossessWithin agree, this is a very clean solution and works for me.Menado
This answer works on IE8-10 as well as modern browsers. The main problem is that it will keep running if the element does not exist - so its best when are you are sure the element is going to be there. Otherwise, you could add a counter.Hargreaves
Worked perfectly for meBerdichev
Worked like charm !!Iago
You were down voted most likely because similar answers exists here and they were posted in 2012 and 2015 e.g. https://mcmap.net/q/73794/-how-to-wait-until-an-element-existsRepellent
They were similar, not identical. Furthermore, many people are doing the same. Lastly, I coded this solution myself. That is a poor reasoning, however, if even it was indeed the case, I'd appreciate a comment letting me know. The answer solves OP's issue and has no apparent motives to be downvoted.Interstate
Your "_waitForElement" function works beautifully. I'm running javascripts in the console and must wait for elements to appear before trying to click them or get their innertext. But it only works great for elements that have an ID. I'm trying to figure out how to adapt it to looping through an array of elements by className to wait until a particular element by innerText exists. The className I'm working with now has 13 different elements. I need to click on one of them. Any suggestions how to modify your function to wait for the element to exist before clickingDominoes
B
29

I think that still there isnt any answer here with easy and readable working example. Use MutationObserver interface to detect DOM changes, like this:

var observer = new MutationObserver(function(mutations) {
    if ($("p").length) {
        console.log("Exist, lets do something");
        observer.disconnect(); 
        //We can disconnect observer once the element exist if we dont want observe more changes in the DOM
    }
});

// Start observing
observer.observe(document.body, { //document.body is node target to observe
    childList: true, //This is a must have for the observer with subtree
    subtree: true //Set to true if changes must also be observed in descendants.
});
            
$(document).ready(function() {
    $("button").on("click", function() {
        $("p").remove();
        setTimeout(function() {
            $("#newContent").append("<p>New element</p>");
        }, 2000);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>New content</button>
<div id="newContent"></div>

Note: Spanish Mozilla docs about MutationObserver are more detailed if you want more information.

Brace answered 7/8, 2019 at 13:8 Comment(1)
Didn't downvoted, but in 2024 this would be a much better answer without jQuery dependencies.Aslant
C
26

You can do

$('#yourelement').ready(function() {

});

Please note that this will only work if the element is present in the DOM when being requested from the server. If the element is being dynamically added via JavaScript, it will not work and you may need to look at the other answers.

Carmen answered 2/4, 2011 at 18:43 Comment(6)
The .ready() function works for most anything (if not anything), not just document. It just won't work with dynamically created elements, even on .live().Remunerate
@Bery, as Richard pointed out, this works only for elements which are already present in the HTML when it's first requested from the server. If Javascript is used to add an element dynamically to the DOM, it doesn't work.Belden
It works perfectly. Just attach it to the reference of the element in memory, not to the string '#yourelement'Jaquelin
@Sam, can you please clarify how to attach it to the reference of the element in memory?Castled
This answer is incorrect. What you're actually checking here is a regular $(document).ready(), not the element you think it will apply too. That's just how this special listener works. ExampleSideburns
This usage is not recommended according to api.jquery.com/readyMathewmathews
F
25

You can listen to DOMNodeInserted or DOMSubtreeModified events which fire whenever a new element is added to the DOM.

There is also LiveQuery jQuery plugin which would detect when a new element is created:

$("#future_element").livequery(function(){
    //element created
});
Farm answered 2/4, 2011 at 18:48 Comment(3)
Very nice plugin! Is there any function like that in jquery directly? I'm wondering that there is no existing feature to do that. And if this is THE plugin, please vote up for this answer ;) For me, it works perfectly. Thank you very much.Olcott
Note IE 9 implements DOMNodeInserted but has a major bug where it won't fire when you add an element for the time, which is most of the time when you'd want to use it. Details are at: help.dottoro.com/ljmcxjla.phpSeeto
DOMSubtreeModified is deprecated in favor of the Mutation Observer APIOchre
F
18

For a simple approach using jQuery I've found this to work well:

  // Wait for element to exist.
  function elementLoaded(el, cb) {
    if ($(el).length) {
      // Element is now loaded.
      cb($(el));
    } else {
      // Repeat every 500ms.
      setTimeout(function() {
        elementLoaded(el, cb)
      }, 500);
    }
  };

  elementLoaded('.element-selector', function(el) {
    // Element is ready to use.
    el.click(function() {
      alert("You just clicked a dynamically inserted element");
    });
  });

Here we simply check every 500ms to see whether the element is loaded, when it is, we can use it.

This is especially useful for adding click handlers to elements which have been dynamically added to the document.

Frodina answered 9/3, 2017 at 10:15 Comment(0)
S
10

How about the insertionQuery library?

insertionQuery uses CSS Animation callbacks attached to the selector(s) specified to run a callback when an element is created. This method allows callbacks to be run whenever an element is created, not just the first time.

From github:

Non-dom-event way to catch nodes showing up. And it uses selectors.

It's not just for wider browser support, It can be better than DOMMutationObserver for certain things.

Why?

  • Because DOM Events slow down the browser and insertionQuery doesn't
  • Because DOM Mutation Observer has less browser support than insertionQuery
  • Because with insertionQuery you can filter DOM changes using selectors without performance overhead!

Widespread support!

IE10+ and mostly anything else (including mobile)

Secret answered 19/9, 2014 at 12:16 Comment(0)
W
10

Here's a function that acts as a thin wrapper around MutationObserver. The only requirement is that the browser support MutationObserver; there is no dependency on JQuery. Run the snippet below to see a working example.

function waitForMutation(parentNode, isMatchFunc, handlerFunc, observeSubtree, disconnectAfterMatch) {
  var defaultIfUndefined = function(val, defaultVal) {
    return (typeof val === "undefined") ? defaultVal : val;
  };

  observeSubtree = defaultIfUndefined(observeSubtree, false);
  disconnectAfterMatch = defaultIfUndefined(disconnectAfterMatch, false);

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.addedNodes) {
        for (var i = 0; i < mutation.addedNodes.length; i++) {
          var node = mutation.addedNodes[i];
          if (isMatchFunc(node)) {
            handlerFunc(node);
            if (disconnectAfterMatch) observer.disconnect();
          };
        }
      }
    });
  });

  observer.observe(parentNode, {
    childList: true,
    attributes: false,
    characterData: false,
    subtree: observeSubtree
  });
}

// Example
waitForMutation(
  // parentNode: Root node to observe. If the mutation you're looking for
  // might not occur directly below parentNode, pass 'true' to the
  // observeSubtree parameter.
  document.getElementById("outerContent"),
  // isMatchFunc: Function to identify a match. If it returns true,
  // handlerFunc will run.
  // MutationObserver only fires once per mutation, not once for every node
  // inside the mutation. If the element we're looking for is a child of
  // the newly-added element, we need to use something like
  // node.querySelector() to find it.
  function(node) {
    return node.querySelector(".foo") !== null;
  },
  // handlerFunc: Handler.
  function(node) {
    var elem = document.createElement("div");
    elem.appendChild(document.createTextNode("Added node (" + node.innerText + ")"));
    document.getElementById("log").appendChild(elem);
  },
  // observeSubtree
  true,
  // disconnectAfterMatch: If this is true the hanlerFunc will only run on
  // the first time that isMatchFunc returns true. If it's false, the handler
  // will continue to fire on matches.
  false);

// Set up UI. Using JQuery here for convenience.

$outerContent = $("#outerContent");
$innerContent = $("#innerContent");

$("#addOuter").on("click", function() {
  var newNode = $("<div><span class='foo'>Outer</span></div>");
  $outerContent.append(newNode);
});
$("#addInner").on("click", function() {
  var newNode = $("<div><span class='foo'>Inner</span></div>");
  $innerContent.append(newNode);
});
.content {
  padding: 1em;
  border: solid 1px black;
  overflow-y: auto;
}
#innerContent {
  height: 100px;
}
#outerContent {
  height: 200px;
}
#log {
  font-family: Courier;
  font-size: 10pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Create some mutations</h2>
<div id="main">
  <button id="addOuter">Add outer node</button>
  <button id="addInner">Add inner node</button>
  <div class="content" id="outerContent">
    <div class="content" id="innerContent"></div>
  </div>
</div>
<h2>Log</h2>
<div id="log"></div>
Wove answered 18/7, 2015 at 9:46 Comment(0)
M
9

You can try this:

const wait_until_element_appear = setInterval(() => {
    if ($(element).length !== 0) {
        // some code
        clearInterval(wait_until_element_appear);
    }
}, 0);

This solution works very good for me

Mercurial answered 30/11, 2020 at 18:11 Comment(1)
Clean and concise. You may want to increase the interval ie. to 500ms, and maybe add a retry counter to avoid infinite loop.Bistort
P
8

Here's a Promise-returning solution in vanilla Javascript (no messy callbacks). By default it checks every 200ms.

function waitFor(selector) {
    return new Promise(function (res, rej) {
        waitForElementToDisplay(selector, 200);
        function waitForElementToDisplay(selector, time) {
            if (document.querySelector(selector) != null) {
                res(document.querySelector(selector));
            }
            else {
                setTimeout(function () {
                    waitForElementToDisplay(selector, time);
                }, time);
            }
        }
    });
}
Paucker answered 18/7, 2018 at 15:50 Comment(0)
B
7

Here's a pure Javascript function which allows you to wait for anything. Set the interval longer to take less CPU resource.

/**
 * @brief Wait for something to be ready before triggering a timeout
 * @param {callback} isready Function which returns true when the thing we're waiting for has happened
 * @param {callback} success Function to call when the thing is ready
 * @param {callback} error Function to call if we time out before the event becomes ready
 * @param {int} count Number of times to retry the timeout (default 300 or 6s)
 * @param {int} interval Number of milliseconds to wait between attempts (default 20ms)
 */
function waitUntil(isready, success, error, count, interval){
    if (count === undefined) {
        count = 300;
    }
    if (interval === undefined) {
        interval = 20;
    }
    if (isready()) {
        success();
        return;
    }
    // The call back isn't ready. We need to wait for it
    setTimeout(function(){
        if (!count) {
            // We have run out of retries
            if (error !== undefined) {
                error();
            }
        } else {
            // Try again
            waitUntil(isready, success, error, count -1, interval);
        }
    }, interval);
}

To call this, for example in jQuery, use something like:

waitUntil(function(){
    return $('#myelement').length > 0;
}, function(){
    alert("myelement now exists");
}, function(){
    alert("I'm bored. I give up.");
});
Bothersome answered 30/11, 2015 at 15:36 Comment(0)
I
7

The observe function below will allow you to listen to elements via a selector.

In the following example, after 2 seconds have passed, a .greeting will be inserted into the .container. Since we are listening to the insertion of this element, we can have a callback that triggers upon insertion.

const observe = (selector, callback, targetNode = document.body) =>
  new MutationObserver(mutations => [...mutations]
    .flatMap((mutation) => [...mutation.addedNodes])
    .filter((node) => node.matches && node.matches(selector))
    .forEach(callback))
  .observe(targetNode, { childList: true, subtree: true });

const createGreeting = () => {
  const el = document.createElement('DIV');
  el.textContent = 'Hello World';
  el.classList.add('greeting');
  return el;
};

const container = document.querySelector('.container');

observe('.greeting', el => console.log('I have arrived!', el), container);

new Promise(res => setTimeout(() => res(createGreeting()), 2000))
  .then(el => container.appendChild(el));
html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
body { display: flex; }
.container { display: flex; flex: 1; align-items: center; justify-content: center; }
.greeting { font-weight: bold; font-size: 2em; }
<div class="container"></div>

Update

Here is an experimental async/await example.

const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

const observe = (selector, targetNode = document.body) =>
  new Promise(res => {
    new MutationObserver(mutations =>
      res([...mutations]
        .flatMap((mutation) => [...mutation.addedNodes])
        .find((node) => node.matches && node.matches(selector))))
    .observe(targetNode, { childList: true, subtree: true });
  });

const createGreeting = () => {
  const el = document.createElement('DIV');
  el.textContent = 'Hello World';
  el.classList.add('greeting');
  return el;
};

const container = document.querySelector('.container');

observe('.greeting', container)
  .then(el => console.log('I have arrived!', el));

(async () => {
  await sleep(2000);
  container.appendChild(createGreeting());
})();
html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
body { display: flex; }
.container { display: flex; flex: 1; align-items: center; justify-content: center; }
.greeting { font-weight: bold; font-size: 2em; }
<div class="container"></div>
Idolism answered 5/1, 2021 at 20:2 Comment(0)
P
6

I usually use this snippet for Tag Manager:

<script>
(function exists() {
  if (!document.querySelector('<selector>')) {
    return setTimeout(exists);
  }
  // code when element exists
})();  
</script>
Peepul answered 23/4, 2020 at 2:33 Comment(0)
T
4

This is a better version written on top of Yong Wang's answer (highest scored answer).

Added feature: you can wait for an element for a particular amount of time with location precision to increase performance.

async function waitForElement(selector, timeout = null, location = document.body) {
    return new Promise((resolve) => {
        let element = document.querySelector(selector);
        if (element) {
            return resolve(element);
        }

        const observer = new MutationObserver(async () => {
            let element = document.querySelector(selector);
            if (element) {
                resolve(element);
                observer.disconnect();
            } else {
                if (timeout) {
                    async function timeOver() {
                        return new Promise((resolve) => {
                            setTimeout(() => {
                                observer.disconnect();
                                resolve(false);
                            }, timeout);
                        });
                    }
                    resolve(await timeOver());
                }
            }
        });

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

Usage:

await waitForElement(".nav-alt", 500, ".main-body")

Bonus: Wait for a element to disappear from DOM.

async function waitForElementDeath(selector, location = document.body) {
    return new Promise((resolve) => {
        const observer = new MutationObserver(async () => {
            if (!document.querySelector(selector)) {
                resolve(true);
                observer.disconnect();
            }
        });

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

Usage:

await waitForElementDeath(".Popup-div", "Popup-Container")
Troublous answered 1/11, 2022 at 3:11 Comment(5)
Nice answer! Small suggestion: it looks like sometimes you're doing querySelector() twice sometimes when you don't need to be (like when your if condition has already verified the element exists)Neddra
in this solution for "Usage" how do you put a callback?Tamie
I didn't use callbacks i just use await waitForElement inside a funtion and it will wait until the element is found and executes the rest. But you can add a callback fuction just below resolve(true) or resolve(element) by creating a parameter in waitForElement funtionTroublous
@Neddra I have used querySelector() just once, it might be specified in two placed but the second one is inside a callback function of MutationObserver. so it will call it again and again whenever there is a MutationTroublous
@RaghavanVidhyasagar My comment was in response to an earlier version of your answerNeddra
H
3

A cleaner example using MutationObserver:

new MutationObserver( mutation => {
    if (!mutation.addedNodes) return
    mutation.addedNodes.forEach( node => {
        // do stuff with node
    })
})
Herder answered 19/10, 2016 at 15:23 Comment(1)
This is not cleaner, it's just incomplete code.Aslant
L
3

A solution returning a Promise and allowing to use a timeout (compatible IE 11+).

For a single element (type Element):

"use strict";

function waitUntilElementLoaded(selector) {
    var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

    var start = performance.now();
    var now = 0;

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

            if (element instanceof Element) {
                clearInterval(interval);

                resolve();
            }

            now = performance.now();

            if (now - start >= timeout) {
                reject("Could not find the element " + selector + " within " + timeout + " ms");
            }
        }, 100);
    });
}

For multiple elements (type NodeList):

"use strict";

function waitUntilElementsLoaded(selector) {
    var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

    var start = performance.now();
    var now = 0;

    return new Promise(function (resolve, reject) {
        var interval = setInterval(function () {
            var elements = document.querySelectorAll(selector);

            if (elements instanceof NodeList) {
                clearInterval(interval);

                resolve(elements);
            }

            now = performance.now();

            if (now - start >= timeout) {
                reject("Could not find elements " + selector + " within " + timeout + " ms");
            }
        }, 100);
    });
}

Examples:

waitUntilElementLoaded('#message', 800).then(function(element) {
    // element found and available

    element.innerHTML = '...';
}).catch(function() {
    // element not found within 800 milliseconds
});

waitUntilElementsLoaded('.message', 10000).then(function(elements) {
    for(const element of elements) {
        // ....
    }
}).catch(function(error) {
    // elements not found withing 10 seconds
});

Works for both a list of elements and a single element.

Landlady answered 10/1, 2019 at 14:48 Comment(2)
My favorite solution! Why check element instanceof HTMLElement? Can it ever be anything other than null or HTMLElement?Nanette
You raise an interesting point. I should have make it broader by using Element instead (fixed). I just make the check because I want to be sure the variable element has the property innerHTML as the Element MDN documentation states. Feel free to remove it if you do not care about it!Landlady
I
3

I have developed an answer inspired by Jamie Hutber's.

It's a promise based function where you can set:

  • maximum number of tries - default 10;
  • delay in milliseconds - default 100 ms.

Therefore, by default, it will wait 1 second until the element appears on the DOM.

If it does not show up it will return a promise.reject with null so you can handle the error as per your wish.

Code

export function _waitForElement(selector, delay = 10, tries = 100) {
  const element = document.querySelector(selector);


  if (!window[`__${selector}`]) {
    window[`__${selector}`] = 0;
    window[`__${selector}__delay`] = delay;
    window[`__${selector}__tries`] = tries;
  }

  function _search() {
    return new Promise((resolve) => {
      window[`__${selector}`]++;
      setTimeout(resolve, window[`__${selector}__delay`]);
    });
  }

  if (element === null) {
    if (window[`__${selector}`] >= window[`__${selector}__tries`]) {
      window[`__${selector}`] = 0;
      return Promise.resolve(null);
    }

    return _search().then(() => _waitForElement(selector));
  } else {
    return Promise.resolve(element);
  }
}

Usage:

async function wait(){
    try{
        const $el = await waitForElement(".llama");
        console.log($el);
    } catch(err){
        console.error("Timeout - couldn't find element.")
    }
} 

wait();

In the example above it will wait for the selector .llama. You can add a greater delay and test it here on the console of StackoverFlow.

Just add the class llama to any element on the DOM.

Interstate answered 9/12, 2020 at 4:22 Comment(0)
F
2

Here is a TypeScript version of Yong Wang's accepted answer using MutationObserver which takes an optional return type that extends from HTMLElement.

This is useful if you need to access element type specific properties (like src on an <img> or href on a <a> link):

function waitFor<T extends HTMLElement>(selector: string): Promise<T> {
  return new Promise((resolve) => {
    const elm = document.querySelector<T>(selector)
    if (elm) return resolve(elm)

    const observer = new MutationObserver((mutations) => {
      const elm = document.querySelector<T>(selector)
      if (elm) {
        resolve(elm)
        observer.disconnect()
      }
    })

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

Usage:

// By default, returns the type "HTMLElement"
const elm = await waitFor('h1')

// Or specify element type if you know it:
const elm = await waitFor<HTMLFormElement>('form')
Foskett answered 27/7, 2023 at 20:3 Comment(0)
E
1

If you want it to stop looking after a while (timeout) then the following jQuery will work. It will time out after 10sec. I needed to use this code rather than pure JS because I needed to select an input via name and was having trouble implementing some of the other solutions.

 // Wait for element to exist.

    function imageLoaded(el, cb,time) {

        if ($(el).length) {
            // Element is now loaded.

            cb($(el));

            var imageInput =  $('input[name=product\\[image_location\\]]');
            console.log(imageInput);

        } else if(time < 10000) {
            // Repeat every 500ms.
            setTimeout(function() {
               time = time+500;

                imageLoaded(el, cb, time)
            }, 500);
        }
    };

    var time = 500;

    imageLoaded('input[name=product\\[image_location\\]]', function(el) {

     //do stuff here 

     },time);
Edmundoedmunds answered 12/8, 2019 at 22:40 Comment(0)
S
1

I try to avoid mutation observers if I can help it, so this is what I came up with. It looks similar to some of the other answers above. This function will look for the first element to exist within a given DOM call -- className being the expected usage but it can also accept tagName or Id. You could also add an argument for a precise index if you were looking for some number of elements with a given classname or tagname to have loaded.

    async function waitUntilElementExits(domkey,domquery,maxtime){
        const delay = (ms) => new Promise(res => setTimeout(res, ms));
        for(let i=0; i<maxtime; i=i+200){
            await delay(200);
            let elm = document[domkey](domquery);
            if( (domkey == 'getElementById' && elm) || elm?.[0] ) break;
        }
    }
    // usage
    await waitUntilElementExits('getElementByClassName','some_class_name',10000)
Stillas answered 11/5, 2022 at 15:15 Comment(2)
"I try to avoid mutation observers" Why?Neddra
It's mostly a matter of preference due to the type of work I perform, but in this particular case, I am not sure it makes sense to listen to the entire DOM tree until an element comes into existence. I am typically building web scrapers and addons, and I find that mutation observers are not reliable when I am not confident about the page behavior. This is why I have a maxtime in my solution. I often need my functions to be "try to do this, but give up if its hard."Stillas
H
1

Instead of querySelector you can also use getElementById

This function is exactly same as https://mcmap.net/q/73794/-how-to-wait-until-an-element-exists

  async function waitForElementById(id, timeout = null, location = document.body) {
    return new Promise((resolve) => {
        let element = document.getElementById(id);
        if (element) {
            return resolve(element);
        }

        const observer = new MutationObserver(async () => {
            let element = document.getElementById(id);
            if (element) {
                resolve(element);
                observer.disconnect();
            } else {
                if (timeout) {
                    async function timeOver() {
                        return new Promise((resolve) => {
                            setTimeout(() => {
                                observer.disconnect();
                                resolve(false);
                            }, timeout);
                        });
                    }
                    resolve(await timeOver());
                }
            }
        });

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

To use it


    waitForElementById("tag_id", 500).then((elm) => {
      console.log(elm)
    })

Or


    var elm = async waitForElementById("tag_id", 500)

Horne answered 16/11, 2022 at 19:31 Comment(1)
This shouldn't be an answer.Aslant
F
1

My take on @Yong Wong's solution, but it has an optional timeout and you can specify the root node from where you'd like to wait for the element.

Full async/await.

const $ = (selector, opts) => {
  let timeout = undefined;
  let root = undefined;

  if (opts) {
    ({ root, timeout } = opts);
  }

  if (root === undefined) root = document.body;
  
  const nodeFound = root.querySelector(selector);
  if (nodeFound) return new Promise(resolve => resolve(nodeFound));

  return new Promise((resolve, reject) => {
    let callback = () => {
      observer.disconnect();
    };

    const _resolve = (node) => {
      callback();
      resolve(node);
    };

    const _reject = (err) => {
      callback();
      reject(err);
    };

    if (timeout && timeout > 0) {
      const handle = setTimeout(() => {
        _reject(new Error("Element not found: timeout exceeded."));
      }, timeout);
      callback = () => {
        observer.disconnect();
        clearTimeout(handle);
      };
    }

    const observer = new MutationObserver(mutations => {
      for (const mutation of mutations) {
        for (const addedNode of mutation.addedNodes) {
          if (addedNode.matches(selector)) {
            _resolve(addedNode);
            return;
          }
        }
      }
    });

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

Example call:

// wait for 10 seconds for 'div.bla-bla-bla' to appear as a child of 'div.some-container'
await $("div.bla-bla-bla", {
  timeout: 10000,
  root: document.querySelector("div.some-container") 
});
Frostwork answered 21/12, 2022 at 12:19 Comment(0)
D
1

Use the arrive.js library written by Uzair Farooq which internally uses the mutation observer api.

Examples from the project's readme:

// watch for creation of an element which satisfies the selector ".test-elem"
document.arrive(".test-elem", function(newElem) {
    // newElem refers to the newly created element
});

// the above event would watch for creation of element in whole document
// it's better to be more specific whenever possible, for example
document.querySelector(".container-1").arrive(".test-elem", function(newElem) {
});

// you can bind event to multiple elements at once
// this will bind arrive event to all the elements returned by document.querySelectorAll()
document.querySelectorAll(".box").arrive(".test-elem", function(newElem) {
});

I read through the other answers and found this library as a comment to another answer.

I had already implemented my own solution using the mutation observer API but I think this library is a better, more thorough implementation of the concept than my solution or many of the others that are snippets but not as fully fleshed out as this library is.

Dibasic answered 19/1 at 21:20 Comment(0)
E
0

Simple Javascript.

cont elementExist = setInterval(() => {
    var elm = document.getElementById("elementId")
    if (elm!=null)
         // call your function here to do something
        clearInterval(elementExist);
    }
}, 100);

Note: This will block other executions

Ebner answered 4/11, 2021 at 7:45 Comment(0)
B
0

I've adapted the function by @YongWang to use a lambda so anything can be used, including XPath:

function waitForElement(findElement) {
  return new Promise(resolve => {
      const elem = findElement();
      if (elem) {
          return resolve(elem);
      }

      const observer = new MutationObserver(_ => {
          const elem = findElement();
          if (elem) {
              observer.disconnect();
              resolve(elem);
          }
      });

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

To use it with async/await and xpath, use this code:

function findByXPath(xpath) {
  return document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

(async() => {
  const btn = await waitForElement(() => findByXPath("//*[text()='foobar']"));
  console.log('button with text foobar appeared: ', btn);
})();
Blanco answered 21/1 at 17:6 Comment(0)
S
0

based on the answer from Yong Wang

const waitForElm = (selector, parentNode = null, timeout = null) => new Promise((resolve, reject) => {
    if (!selector) reject("no selector");
    if (!parentNode) parentNode = globalThis.document.body;
    for (const res = parentNode.querySelector(selector);;) {
        if (res) return resolve(res);
        break;
    }
    let timeoutID = null;
    const observer = new MutationObserver(mutations => {
        const res = mutations.addedNodes.find(
            node => node.matchesSelector(selector));
        if (res) {
            if (timeoutID) clearTimeout(timeoutID);
            observer.disconnect();
            resolve(res);
        }
    });
    timeoutID = timeout ? setTimeout(() => {
        observer.disconnect();
        reject("timeout");
    }, timeout) : null;
    // If you get "parameter 1 is not of type 'Node'" error
    // see https://mcmap.net/q/75048/-39-observe-39-on-39-mutationobserver-39-parameter-1-is-not-of-type-39-node-39
    observer.observe(parentNode, {
        childList: true,
        subtree: true
    });
});
Scotticism answered 1/2 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.