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

瀏覽器相容性

另見