MutationObserver
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Das MutationObserver
-Interface bietet die Möglichkeit, Änderungen im DOM-Baum zu beobachten. Es ist als Ersatz für das ältere Mutation Events-Feature konzipiert, das Teil der DOM3-Events-Spezifikation war.
Konstruktor
MutationObserver()
-
Erstellt und gibt einen neuen
MutationObserver
zurück, der eine angegebene Callback-Funktion aufruft, wenn Änderungen am DOM auftreten.
Instanzmethoden
disconnect()
-
Stoppt die
MutationObserver
-Instanz davon, weitere Benachrichtigungen zu erhalten, bis und sofernobserve()
erneut aufgerufen wird. observe()
-
Konfiguriert den
MutationObserver
, um Benachrichtigungen über seine Callback-Funktion zu empfangen, wenn Änderungen im DOM auftreten, die den angegebenen Optionen entsprechen. takeRecords()
-
Entfernt alle ausstehenden Benachrichtigungen aus der Benachrichtigungswarteschlange des
MutationObserver
und gibt sie in einem neuenArray
vonMutationRecord
-Objekten zurück.
Beispiel
Das folgende Beispiel wurde aus diesem Blogbeitrag adaptiert.
// 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();
Spezifikationen
Specification |
---|
DOM # interface-mutationobserver |