MutationObserver example

by luwes

HTML

<div id="target" foo="bar"></div>
<br />
<button id="addBtn">Add element</button>
<button id="changeAttributeBtn">Add Attribute</button>
<br />
<br />
<div class="console"></div>

CSS

#target {
    border: 1px solid red;
    padding:5px;
}

.console {
    border: 1px solid lightgrey;
    padding:5px;
}

JavaScript

// select the target node
var target = document.getElementById('target');

var addBtn = document.getElementById('addBtn');
var changeAttributeBtn = document.getElementById('changeAttributeBtn');

addBtn.addEventListener('click', function () {
    target.innerHTML = "<my-custom-element>Child</my-custom-element>"
});

changeAttributeBtn.addEventListener('click', function () {
    target.setAttribute('foo', 99);
    target.setAttribute('foos', [1, 2, 3]);
});




// create an observer instance
var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        console.log(mutation);
        
        var p = document.createElement("p");
        p.innerHTML = "type: " + mutation.type + "<br />" +
            "target id: " + mutation.target.id + "<br />" +
            "target attribute foo: " + mutation.target.attributes['foo'].value + "<br />";
            
        console.log(mutation, mutation.target.attributes['foo'].value)
            
        document.querySelector('.console').appendChild(p);
    });
});

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

// later, you can stop observing
//observer.disconnect();