Skip to content

Latest commit

 

History

History
50 lines (38 loc) · 1.78 KB

mutation.observer.md

File metadata and controls

50 lines (38 loc) · 1.78 KB

Mutation Observer 📕

importance

MutationObserver interface provides the ability to watch for changes being made to the DOM tree Invokes a specified callback function when DOM changes occur. When the callback is triggered, it is supplied a list of the changes to the DOM, which you can then loop through and choose to react to.

disconnect()

Stops the MutationObserver instance from receiving further notifications until and unless observe() is called again.

observe()

Configures the MutationObserver to begin receiving notifications through its callback function when DOM changes matching the given options occur.

takeRecords()

Removes all pending notifications from the MutationObserver's notification queue and returns them in a new Array of MutationRecord objects.

example

/ Select the node that will be observed for mutations
  const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
    const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
  const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    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.`);
    }
  }
  };

    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);

    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);

    // Later, you can stop observing
    observer.disconnect();