Files
30-seconds-of-code/snippets/observeMutations.md
2018-01-13 14:58:52 +02:00

913 B

observeMutations

Runs the provided callback for each mutation on the specified element.

Use a MutationObserver to observe mutations on the given element. Use Array.forEach() to run the callback for each mutation that is observed. Omit the third argument, options, to use the default options (all true).

const observeMutations = (element, callback, options) => new MutationObserver(mutations => mutations.forEach(m => callback(m))).observe(element, Object.assign(
  {
    childList: true,
    attributes: true,
    attributeOldValue: true,
    characterData: true,
    characterDataOldValue: true,
    subtree: true
  }, options));
observeMutations(document, console.log); // Logs all mutations that happen on the page