如何等到元素存在?

时间:2011-04-02 18:32:18

标签: javascript jquery google-chrome google-chrome-extension

22 个答案:

答案 0 :(得分:128)

由于性能问题,

DOMNodeInserted以及其他DOM突变事件已被弃用 - 推荐的方法是使用MutationObserver来监视DOM。它仅在较新的浏览器中受支持,因此当DOMNodeInserted不可用时,您应该回到MutationObserver

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:
observer.disconnect()

答案 1 :(得分:109)

我遇到了同样的问题,所以我继续为它写了plugin

$(selector).waitUntilExists(function);

代码:

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

答案 2 :(得分:60)

这是一个等待显示元素的核心JavaScript函数。

参数:

  1. selector:此函数查找元素$ {selector}
  2. time:此函数检查此元素是否每隔$ {time}毫秒存在。

    function waitForElementToDisplay(selector, time) {
            if(document.querySelector(selector)!=null) {
                alert("The element is displayed, you can put your code instead of this alert.")
                return;
            }
            else {
                setTimeout(function() {
                    waitForElementToDisplay(selector, time);
                }, time);
            }
        }
    
  3. 例如,设置selector="#div1"time=5000会查找每5000毫秒id="div1"的HTML标记。

答案 3 :(得分:24)

您可以收听在将新元素添加到DOM时触发的DOMNodeInsertedDOMSubtreeModified个事件。

还有LiveQuery jQuery插件可以检测创建新元素的时间:

$("#future_element").livequery(function(){
    //element created
});

答案 4 :(得分:21)

你可以做到

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

});

请注意,只有在从服务器请求DOM中存在元素时,这才有效。如果通过JavaScript动态添加元素,它将无法工作,您可能需要查看其他答案。

答案 5 :(得分:14)

我使用这种方法等待一个元素出现,所以我可以在那之后执行其他函数。

假设doTheRestOfTheStuff(parameters)函数只应在ID为the_Element_ID的元素出现或完成加载后调用,我们可以使用,

var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms

答案 6 :(得分:11)

对于那些习惯于承诺并且不想使用任何第三方库或计时器的人来说,这是一个简单的解决方案。

我已经在我的项目中使用了一段时间

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)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

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

要使用它:

waitForElm('.some-class').then(elm => console.log(elm.textContent));

或使用async / await

const elm = await waitForElm('.some-classs')

答案 7 :(得分:8)

insertionQuery图书馆怎么样?

insertQuery使用附加到指定选择器的CSS动画回调来在创建元素时运行回调。此方法允许在创建元素时运行回调,而不仅仅是第一次。

来自github:

  

捕捉节点出现的非dom-event方式。它使用选择器。

     

这不仅仅适用于更广泛的浏览器支持,对于某些事情来说,它可能比DOMMutationObserver更好。

     

为什么?

     
      
  • 因为DOM事件会降低浏览器的速度而且insertQuery不会
  •   
  • 因为DOM Mutation Observer的浏览器支持少于insertionQuery
  •   
  • 因为使用insertQuery,您可以使用选择器过滤DOM更改,而不会产生性能开销!
  •   
     

广泛的支持!

     

IE10 +以及其他任何东西(包括移动设备)

答案 8 :(得分:8)

对于使用jQuery的简单方法,我发现这很好用:

  // 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");
    });
  });

这里我们只需检查每500ms以查看元素是否已加载,如果已加载,我们可以使用它。

这对于将点击处理程序添加到已动态添加到文档中的元素特别有用。

答案 9 :(得分:5)

这是一个充当MutationObserver的瘦包装器的函数。唯一的要求是浏览器支持MutationObserver;没有依赖于JQuery。运行下面的代码段以查看一个有效的示例。

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>

答案 10 :(得分:4)

这是使用原始Javascript的Promise返回解决方案(没有混乱的回调)。默认情况下,它每200毫秒检查一次。

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);
            }
        }
    });
}

答案 11 :(得分:3)

这是一个纯粹的Javascript函数,可以让你等待任何事情。将时间间隔设置得更长,以减少CPU资源。

/**
 * @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);
}

要调用它,例如在jQuery中,请使用类似:

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

答案 12 :(得分:2)

使用MutationObserver的简洁示例:

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

答案 13 :(得分:2)

我认为,这里没有简单易懂的工作示例的答案。使用MutationObserver interface来检测DOM更改,如下所示:

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>

  

注意:关于MutationObserver的{​​{3}}文档更多   如果需要更多信息,则为详细信息。

答案 14 :(得分:1)

返回Promise并允许使用超时(兼容IE 11+)的解决方案:

"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 HTMLElement) {
                clearInterval(interval);

                resolve();
            }

            now = performance.now();

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

"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);
    });
}

示例:

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
});

适用于元素列表和单个元素。

答案 15 :(得分:1)

如果您希望它在一段时间(超时)后停止寻找,则以下jQuery将起作用。它将在10秒后超时。我需要使用此代码而不是纯JS,因为我需要通过名称选择输入,并且在实现其他一些解决方案时遇到麻烦。

 // 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);

答案 16 :(得分:1)

我通常将此代码段用于跟踪代码管理器:

http://localhost:8000/verification/:id

答案 17 :(得分:1)

我从Jamie Hutber's得到了启发。

这是一个基于承诺的功能,您可以在其中进行设置:

  • 最大尝试次数-默认为ViewModel(title: "some value") ;
  • 延迟(以毫秒为单位)-默认为100 ms

因此,默认情况下,它将等待1秒钟,直到元素出现在DOM上。

如果未显示,它将返回带有10的{​​{1}},因此您可以根据需要处理错误。

代码

promise.reject

用法

null

在上面的示例中,它将等待选择器 function waitForElement(selector, delay = 1000, tries = 10) { const element = document.querySelector(selector); // creates a local variable w/ the name of the selector to keep track of all tries if (!window[`__${selector}`]) { window[`__${selector}`] = 0; } function _search() { return new Promise((resolve) => { window[`__${selector}`]++; console.log(window[`__${selector}`]); setTimeout(resolve, delay); }); } //element not found, retry if (element === null) { if (window[`__${selector}`] >= tries) { window[`__${selector}`] = 0; return Promise.reject(null); } return _search().then(() => waitForElement(selector)); } else { return Promise.resolve(element); } } 。您可以在StackoverFlow的控制台上添加更大的延迟并对其进行测试。

只需将类async function wait(){ try{ const $el = await waitForElement(".llama"); console.log($el); } catch(err){ console.error("Timeout - couldn't find element.") } } wait(); 添加到DOM上的任何元素。

答案 18 :(得分:1)

下面的 observe 函数将允许您通过选择器监听元素。

在以下示例中,经过 2 秒后,.greeting 将插入到 .container 中。因为我们正在监听这个元素的插入,所以我们可以有一个在插入时触发的回调。

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>

答案 19 :(得分:0)

只需添加所需的选择器。一旦找到该元素,您就可以在回调函数中进行访问。

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

答案 20 :(得分:0)

您可以尝试以下方法:

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

此解决方案对我来说非常有用

答案 21 :(得分:-2)

如果您有异步dom更改,此功能将检查DOM元素(以秒为单位的时间限制),对于DOM及其基于Promise的内容来说,它并不繁琐:)

function getElement(selector, i = 5) {
  return new Promise(async (resolve, reject) => {
    if(i <= 0) return reject(`${selector} not found`);
    const elements = document.querySelectorAll(selector);
    if(elements.length) return resolve(elements);
    return setTimeout(async () => await getElement(selector, i-1), 1000);
  })
}

// Now call it with your selector

try {
  element = await getElement('.woohoo');
} catch(e) { // catch the e }

//OR

getElement('.woohoo', 5)
.then(element => { // do somthing with the elements })
.catch(e => { // catch the error });