A custom element that offers a declarative interface to the MutationObserver API.
The following examples demonstrate how to use the <mutation-observer>
custom element to observe changes to the DOM.
Observing attributes changes: class
<mutation-observer attr="class" attr-old-value>
<button class="btn-primary">
Click to mutate me
</button>
</mutation-observer>
<script>
const mutationObserverEl = document.querySlector('mutation-observer');
const button = mutationObserverEl.querySelector('button');
const classNames = ['primary', 'secondary', 'success', 'danger', 'warning', 'info'];
let count = 0;
button.addEventListener('click', evt => {
count += 1;
evt.target.className = `btn-${classNames[count % classNames.length]}`;
});
mutationObserverEl.addEventListener('mutation-observer:mutate', evt => {
console.log('mutation-observer:mutate ->', evt.detail);
});
</script>
Observing addition of new child nodes or removal of existing child nodes
<button id="addButton">Add element</button>
<button id="removeButton">Remove element</button>
<mutation-observer child-list>
<div id="elementsContainer"></div>
</mutation-observer>
<script>
const mutationObserverEl = document.querySlector('mutation-observer');
const addButton = document.getElementById('addButton');
const removeButton = document.getElementById('removeButton');
const elementsContainer = document.getElementById('elementsContainer');
let count = 0;
addButton.addEventListener('click', () => {
const el = document.createElement('div');
el.textContent = ++count;
elementsContainer.appendChild(el);
});
removeButton.addEventListener('click', () => {
const lastElement = elementsContainer.querySelector('div :last-child');
if (lastElement) {
count -= 1;
lastElement.remove();
}
});
mutationObserverEl.addEventListener('mutation-observer:mutate', evt => {
console.log('mutation-observer:mutate ->', evt.detail);
});
</script>
Observing changes to the character data contained within the node
<mutation-observer char-data char-data-old-value>
<div contenteditable="true">
Type into this content editable element to watch for mutations.
</div>
</mutation-observer>
<script>
const mutationObserverEl = document.querySlector('mutation-observer');
mutationObserverEl.addEventListener('mutation-observer:mutate', evt => {
console.log('mutation-observer:mutate ->', evt.detail);
});
</script>