DOM MutationObserver

Observe DOM mutations.

by Julien Etienne

HTML

<div id="some-id">
    <input type="button" value="Click" onclick="duplicate()" />
    <div></div>
</div>

CSS

#some-id>div {
    width: 16px;
    height: 16px;
    background: red;
    margin: 3px;
}

JavaScript

var target = document.querySelector('#some-id');

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


function duplicate() {
    target.appendChild(document.createElement("DIV"));
}

setTimeout(() => {
	target.addEventListener('click', ()=> console.log('click'))
}, 2000)