How to wait until an element exists?

后端 未结 19 1776
广开言路
广开言路 2020-11-22 09:14

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 t

19条回答
  •  -上瘾入骨i
    2020-11-22 09:35

    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("

    New element

    "); }, 2000); }); });
    
    
    
    

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

提交回复
热议问题