# MutationObserver

The `MutationObserver` interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

## 1. The Concept

A `MutationObserver` allows you to react to changes in the DOM, such as:
*   Elements being added or removed.
*   Attributes being modified.
*   Text content changing.

Unlike Mutation Events (which were synchronous and fired for every single change, causing performance issues), `MutationObserver` is asynchronous. It waits until the end of the current script execution and reports a batch of changes in one go.

## 2. Basic Usage

To use it, create an observer instance with a callback function, and then call `observe()` on a target node.

```javascript
// 1. Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// 2. Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// 3. Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    for(const mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// 4. Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// 5. Start observing the target node for configured mutations
observer.observe(targetNode, config);
```

## 3. Configuration Options

The configuration object passed to `observe()` defines what you want to look for:

*   `childList`: Set to `true` to monitor the target node for the addition of new child nodes or removal of existing child nodes.
*   `attributes`: Set to `true` to watch for changes to the value of attributes on the target node.
*   `characterData`: Set to `true` to monitor the target node for changes to the character data contained within the node.
*   `subtree`: Set to `true` to extend monitoring to the entire subtree of nodes rooted at the target node.
*   `attributeOldValue`: Set to `true` to record the previous value of any attribute that changes.
*   `characterDataOldValue`: Set to `true` to record the previous value of character data that changes.
*   `attributeFilter`: An array of specific attribute names to be monitored. If this property isn't included, changes to all attributes cause mutation notifications.

## 4. Methods

*   `observe(target, options)`: Configures the `MutationObserver` to begin receiving notifications through its callback function when DOM changes matching the given options occur.
*   `disconnect()`: Stops the `MutationObserver` instance from receiving further notifications until `observe()` is called again.
*   `takeRecords()`: Removes all pending notifications from the `MutationObserver`'s notification queue and returns them in a new Array of `MutationRecord` objects.

## 5. Example: Stopping Observation

```javascript
// Later, you can stop observing
observer.disconnect();
```

## 6. Use Cases

*   **Syntax Highlighting:** Re-running a highlighter when code blocks are dynamically inserted.
*   **Ad Blocking/Anti-Ad Blocking:** Detecting when elements are removed or hidden.
*   **Framework Integration:** Reacting to changes made by third-party libraries that manipulate the DOM directly.

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/dom-manipulation]]
[[programming/javascript/vanilla/intersection-observer]]