Mutation Observers in JavaScript with Code Example

Mutation Observers are a powerful tool for detecting and reacting to changes in the DOM (Document Object Model). They allow you to observe specific elements or subtrees of the DOM and receive notifications whenever changes are made to them. This can be useful for a variety of purposes, such as detecting updates to a form or table, reacting to changes in the layout or style of an element, or synchronizing data between the DOM and an application state.

To use Mutation Observers, you first need to create a new MutationObserver object and specify a callback function that will be called whenever a mutation is detected. The callback function receives a list of MutationRecord objects, which describe the details of the mutation, such as the type of mutation (e.g. an element being added or removed), the target element, and any related nodes or attributes.

Here’s an example of how you might use a MutationObserver to detect changes to a table:

const table = document.querySelector('table');

const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if (mutation.type === 'childList') {
      console.log('The table has changed!');
    }
  });
});

observer.observe(table, {
  childList: true,
  subtree: true
});

In this example, the observer is set up to listen for changes to the children of the table element (childList: true) and to also listen for changes to the descendants of the table element (subtree: true). When any changes are detected, the callback function will be called and will log a message to the console.

You can customize the behavior of the observer by specifying which types of mutations you want to observe and by filtering the mutations based on their target element or other criteria. For example, you could modify the observer to only listen for changes to the rows of the table by using the attributeFilter option, or to only log a message when a certain element is added or removed by using the mutation.target property.

Mutation Observers can be a useful tool for detecting and reacting to changes in the DOM, but it’s important to use them judiciously. They can have a performance impact on your page if you use them heavily or observe a large number of elements, so it’s important to consider alternative approaches when possible.

Overall, Mutation Observers are a powerful and flexible way to detect and react to changes in the DOM, and can be a valuable addition to your toolkit when building web applications.