Skip to main content
Default Gray Amethyst

Mutation Observer

<mo-mutation-observer> | MOMutationObserver
Since 1.0 stable

A component that watches for mutations to a node.

The mutation observer will report changes to the content it wraps through the mo-mutation event. When emitted, a collection of MutationRecord objects will be attached to event.detail that contains information about how it changed.

Click to mutate
Click the button to change variant and watch the console
<div class="mutation-overview">
  <mo-mutation-observer attr="variant">
    <mo-button variant="primary">Click to mutate</mo-button>
  </mo-mutation-observer>

  <br />
  <div style="display: flex; align-items: center; gap: 4px;">
    <mo-icon name="arrow-up"></mo-icon> Click the button to change variant and watch the console
  </div>

  <script>
    const container = document.querySelector('.mutation-overview');
    const mutationObserver = container.querySelector('mo-mutation-observer');
    const button = container.querySelector('mo-button');
    const variants = ['primary', 'secondary', 'subtle'];
    let clicks = 0;

    // Change the button's variant attribute
    button.addEventListener('click', () => {
      clicks++;
      button.setAttribute('variant', variants[clicks % variants.length]);
    });

    // Log mutations
    mutationObserver.addEventListener('mo-mutation', event => {
      console.log(event.detail);
    });
  </script>

  <style>
    .mutation-overview mo-button {
      margin-bottom: 1rem;
    }
  </style>
</div>
import { useState } from 'react';
import { MOButton, MOMutationObserver } from '@metsooutotec/modes-web-components/dist/react';

const css = `
  .resize-observer-overview div {
    display: flex;
    border: solid 2px var(--mo-input-border-color);
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 4rem 2rem;
  }
`;

const variants = ['primary', 'secondary', 'subtle'];
let clicks = 0;

const App = () => {
  const [variant, setVariant] = useState('primary');

  function handleClick() {
    clicks++;
    setVariant(variants[clicks % variants.length]);
  }

  return (
    <>
      <MOMutationObserver attr="*" onMoMutation={event => console.log(event.detail)}>
        <MOButton variant={variant} onClick={handleClick}>
          Click to mutate
        </MOButton>
      </MOMutationObserver>

      <style>{css}</style>
    </>
  );
};

Examples

Child list

Use the child-list attribute to watch for new child elements that are added or removed.

Add button
Add and remove buttons and watch the console
<div class="mutation-child-list">
  <mo-mutation-observer child-list>
    <div class="buttons">
      <mo-button variant="primary">Add button</mo-button>
    </div>
  </mo-mutation-observer>

  <div style="display: flex; align-items: center; gap: 4px;">
    <mo-icon name="arrow-up"></mo-icon> Add and remove buttons and watch the console
  </div>

  <script>
    const container = document.querySelector('.mutation-child-list');
    const mutationObserver = container.querySelector('mo-mutation-observer');
    const buttons = container.querySelector('.buttons');
    const button = container.querySelector('mo-button[variant="primary"]');
    let i = 0;

    // Add a button
    button.addEventListener('click', () => {
      const button = document.createElement('mo-button');
      button.textContent = ++i;
      buttons.append(button);
    });

    // Remove a button
    buttons.addEventListener('click', event => {
      const target = event.target.closest('mo-button:not([variant="primary"])');
      event.stopPropagation();

      if (target) {
        target.remove();
      }
    });

    // Log mutations
    mutationObserver.addEventListener('mo-mutation', event => {
      console.log(event.detail);
    });
  </script>

  <style>
    .mutation-child-list .buttons {
      display: flex;
      gap: 0.25rem;
      flex-wrap: wrap;
      margin-bottom: 1rem;
    }
  </style>
</div>
import { useState } from 'react';
import { MOButton, MOMutationObserver } from '@metsooutotec/modes-web-components/dist/react';

const css = `
  .mutation-child-list .buttons {
    display: flex;
    gap: .25rem;
    flex-wrap: wrap;
    margin-bottom: 1rem;
  }
`;

let buttonCount = 0;

const App = () => {
  const [buttonIds, setButtonIds] = useState([]);

  function addButton() {
    setButtonIds([...buttonIds, ++buttonCount]);
  }

  function removeButton(id) {
    setButtonIds(buttonIds.filter(i => i !== id));
  }

  return (
    <>
      <div className="mutation-child-list">
        <MOMutationObserver child-list onMoMutation={event => console.log(event.detail)}>
          <div className="buttons">
            <MOButton variant="primary" onClick={addButton}>
              Add button
            </MOButton>
            {buttonIds.map(id => (
              <MOButton key={id} variant="default" onClick={() => removeButton(id)}>
                {id}
              </MOButton>
            ))}
          </div>
        </MOMutationObserver>
      </div>
      👆 Add and remove buttons and watch the console
      <style>{css}</style>
    </>
  );
};

Importing

If you’re using the autoloader or the traditional loader, you can ignore this section. Otherwise, feel free to use any of the following snippets to cherry pick this component.

Bundler React Script

To import this component using a bundler:

import '@metsooutotec/modes-web-components/dist/components/mutation-observer/mutation-observer.js';

To import this component as a React component:

import MOMutationObserver from '@metsooutotec/modes-web-components/dist/react/mutation-observer/';

To import this component using a script tag:

<script type="module" src="https://modes-web.metso.com/dist/components/cdn/components/mutation-observer/mutation-observer.js"></script>

Slots

Name Description
(default) The content to watch for mutations.

Learn more about using slots.

Properties

Name Description Reflects Type Default
attr Watches for changes to attributes. To watch only specific attributes, separate them by a space, e.g. class id title. To watch all attributes, use *. string -
attrOldValue
attr-old-value
Indicates whether or not the attribute’s previous value should be recorded when monitoring changes. boolean false
charData
char-data
Watches for changes to the character data contained within the node. boolean false
charDataOldValue
char-data-old-value
Indicates whether or not the previous value of the node’s text should be recorded. boolean false
childList
child-list
Watches for the addition or removal of new child nodes. boolean false
disabled Disables the observer. boolean false
updateComplete A read-only promise that resolves when the component has finished updating.

Learn more about attributes and properties.

Events

Name React Event Description Event Detail
mo-mutation onMoMutation Emitted when a mutation occurs. -

Learn more about events.