<mutation-observer>

A custom element that offers a declarative interface to the MutationObserver API.

Source code & documentation

Examples

The following examples demonstrate how to use the <mutation-observer> custom element to observe changes to the DOM.

  1. Observing attributes changes
  2. Observing addition of new child nodes or removal of existing child nodes
  3. Observing changes to the character data contained within the node
Open the browser's console to watch emitted events.

# Example 1

Observing attributes changes: class

Source code
<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>

# Example 2

Observing addition of new child nodes or removal of existing child nodes

Source code
<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>

# Example 3

Observing changes to the character data contained within the node

Type into this content editable element to watch for mutations.
Source code
<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>

License

The MIT License (MIT)