javascript - variable - when element exists

How to wait until an element exists? (8)

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.

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (!mutation.addedNodes) return

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

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

// stop watching using:

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?

A cleaner example using MutationObserver:

new MutationObserver( mutation => {
    if (!mutation.addedNodes) return
    mutation.addedNodes.forEach( node => {
        // do stuff with node

Here is a core JavaScript function to wait for the display of an element.


  1. selector: This function looks for the element ${selector}
  2. time: This function checks whether this element exists every ${time} milliseconds.

    function waitForElementToDisplay(selector, time) {
            if(document.querySelector(selector)!=null) {
                alert("The element is displayed, you can put your code instead of this alert.")
            else {
                setTimeout(function() {
                    waitForElementToDisplay(selector, time);
                }, time);

As an example, setting selector="#div1" and time=5000 will look for the HTML tag whose id="div1" every 5000 milliseconds.

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) {
            else {
                setTimeout(function () {
                    waitForElementToDisplay(selector, time);
                }, time);

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()) {
    // The call back isn't ready. We need to wait for it
        if (!count) {
            // We have run out of retries
            if (error !== undefined) {
        } else {
            // Try again
            waitUntil(isready, success, error, count -1, interval);
    }, interval);

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

    return $('#myelement').length > 0;
}, function(){
    alert("myelement now exists");
}, function(){
    alert("I'm bored. I give up.");

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.


  • 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)

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



;(function ($, window) {

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

    if (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
    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
        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));

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.