Search code examples
javascriptjqueryknockout.jssingle-page-applicationmutation-observers

How to detect whether an dom element has loaded on the page


I have a single page application where a div with a class "abc" is getting loaded dynamically. I want to run a script only after that particular element and all its children have been loaded in the DOM. I don't want to use a timer which calls the function again and again. How do I go about this. This is probably related to mutation observer but I am not understanding how to use that.


Solution

  • Example with mutation observer

    var target = document.querySelector('.class');
    
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });
    });
    
    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: true }
    
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    

    So for each mutation of the target element this code console.log(mutation.type); will be execute