Detect added element to DOM with Mutation Observer

Here’s a simple example of how you can use a MutationObserver to listen for when an element is added to the DOM.

For brevity, I’m using jQuery syntax to build the node and insert it into the DOM.

var myElement = $("<div>hello world</div>")[0];

var observer = new MutationObserver(function(mutations) {
   if (document.contains(myElement)) {
        console.log("It's in the DOM!");
        observer.disconnect();
    }
});

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

$("body").append(myElement); // console.log: It's in the DOM!

You don’t need to iterate over each MutationRecord stored in mutations because you can perform the document.contains check directly upon myElement.

Leave a Comment