MutationObserver: takeRecords() method
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.
TheMutationObserver methodtakeRecords() returns a list of all matching DOM changesthat have been detected but not yet processed by the observer's callback function,leaving the mutation queue empty.
The most common use case for this is toimmediately fetch all pending mutation records immediately prior to disconnecting theobserver, so that any pending mutations can be processed when shutting down theobserver.
In this article
Syntax
takeRecords()Parameters
None.
Return value
An array ofMutationRecord objects, each describing one change applied tothe observed portion of the document's DOM tree.
Note:The queue of mutations which have occurred, but not beendelivered to the observer's callback is left empty after callingtakeRecords().
Examples
In this example, we demonstrate how to handle any undeliveredMutationRecords by callingtakeRecords() just beforedisconnecting the observer.
const targetNode = document.querySelector("#someElement");const observerOptions = { childList: true, attributes: true,};const observer = new MutationObserver(callback);observer.observe(targetNode, observerOptions);/* later, when it's time to stop observing… *//* handle any still-pending mutations */let mutations = observer.takeRecords();observer.disconnect();if (mutations.length > 0) { callback(mutations);}The code fetches any unprocessed mutation records, then invokes thecallback with the records so that they can be processed. This is done immediately priorto callingdisconnect() to stop observingthe DOM.
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-mutationobserver-takerecords①> |