MutationObserver

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

MutationObserver 接口提供了监视 DOM 树变化的机制。它是为了取代旧的 Mutation Events 功能而设计的,后者是 DOM3 Events 规范的一部分。

构造函数

MutationObserver()

创建一个新的 MutationObserver 实例并返回,当 DOM 发生变化时,它会调用指定的 callback 函数。

实例方法

disconnect()

停止 MutationObserver 实例接收后续通知,直到(且除非)再次调用 observe() 方法。

observe()

配置 MutationObserver,使其在发生与给定选项匹配的 DOM 更改时,开始通过其 callback 函数接收通知。

takeRecords()

MutationObserver 的通知队列中移除所有待处理的通知,并以 MutationRecord 对象的 Array 形式返回它们。

示例

以下示例改编自 这篇博客文章

js
// 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();

规范

规范
DOM
# interface-mutationobserver

浏览器兼容性

另见