Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. MutationObserver
  4. observe()

MutationObserver: observe() 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 methodobserve() configures theMutationObservercallback to begin receiving notifications of changes to the DOM that match the given options.

Depending on the configuration, the observer may watch a singleNode in the DOM tree, or that node and some or all of its descendant nodes. The same node can be observed by multiple observers, and the sameMutationObserver can watch for changes to different parts of the DOM tree and/or different types of changes by callingobserve() multiple times on the sameMutationObserver.

To stop theMutationObserver (so that none of its callbacks will be triggered any longer), callMutationObserver.disconnect().

Syntax

js
observe(target, options)

Parameters

target

A DOMNode (which may be anElement) within the DOMtree to watch for changes, or to be the root of a subtree of nodes to be watched.

options

An object providing options that describe which DOM mutations should be reported tomutationObserver'scallback.At a minimum, one ofchildList,attributes, and/orcharacterData must betrue when you callobserve().Otherwise, aTypeError exception will be thrown.

Options are as follows:

subtreeOptional

Set totrue to extend monitoring to the entire subtree of nodes rooted attarget.All of the other properties are then extended to all of the nodes in the subtree instead of applying solely to thetarget node. The default value isfalse. Note that if a descendant oftarget is removed, changes in that descendant subtree will continue to be observed, until the notification about the removal itself has been delivered.

childListOptional

Set totrue to monitor the target node (and, ifsubtree istrue, its descendants) for the addition of new child nodes or removal of existing child nodes.The default value isfalse.

attributesOptional

Set totrue to watch for changes to the value of attributes on the node or nodes being monitored. The default value istrue if either ofattributeFilter orattributeOldValue is specified, otherwise the default value isfalse.

attributeFilterOptional

An array of specific attribute names to be monitored.If this property isn't included, changes to all attributes cause mutation notifications.

attributeOldValueOptional

Set totrue to record the previous value of any attribute that changes when monitoring the node or nodes for attribute changes;SeeMonitoring attribute values for an example of watching for attribute changes and recording values.The default value isfalse.

characterDataOptional

Set totrue to monitor the specified target node (and, ifsubtree istrue, its descendants) for changes to the character data contained within the node or nodes.The default value istrue ifcharacterDataOldValue is specified, otherwise the default value isfalse.

characterDataOldValueOptional

Set totrue to record the previous value of a node's text whenever the text changes on nodes being monitored.The default value isfalse.

Return value

None (undefined).

Exceptions

TypeError

Thrown in any of the following circumstances:

  • Theoptions are configured such that nothing will actually be monitored.(For example, ifchildList,attributes, andcharacterData are allfalse.)
  • The value ofoptions.attributes isfalse (indicating that attribute changes are not to be monitored), butattributeOldValue istrue and/orattributeFilter is present.
  • ThecharacterDataOldValue option istrue butcharacterData isfalse (indicating that character changes are not to be monitored).

Examples

Basic usage

In this example, we demonstrate how to call the methodobserve() on an instance ofMutationObserver, once it has been set up, passing it a target elementand anoptions object.

js
// create a new instance of `MutationObserver` named `observer`,// passing it a callback functionconst observer = new MutationObserver(() => {  console.log("callback that runs when observer is triggered");});// call `observe()`, passing it the element to observe, and the options objectobserver.observe(document.querySelector("#element-to-observe"), {  subtree: true,  childList: true,});

Removed descendants when usingsubtree

If you watch a node using thesubtree option, you will continue to receive notifications of changes to the descendants of the node, even after a part of the subtree is removed. However, once the notification about the removal is delivered, further changes to the detached subtree will no longer trigger the observer.

This prevents you from missing changes that occur after the connection is severed and before you have a chance to specifically begin monitoring the moved node or subtree for changes. Theoretically, this means that if you keep track of theMutationRecord objects describing the changes that occur, you should be able to "undo" the changes,rewinding the DOM back to its initial state.

html
<div>  <div></div></div>
js
const target = document.getElementById("target");const child = document.getElementById("child");const observer = new MutationObserver((mutations) => {  mutations.forEach((mutation) => {    console.log(mutation.type, mutation.target.id, mutation.attributeName);    if (mutation.type === "childList" && mutation.target.id === "target") {      // After receiving the notification that the child was removed,      // further modifications to the detached subtree no longer trigger the observer.      child.setAttribute("data-bar", "");    }  });});observer.observe(target, {  attributes: true,  childList: true,  subtree: true,});target.removeChild(child);// This change happens before the "childList target" notification is delivered,// so it will also trigger the observer.child.setAttribute("data-foo", "");// Output:// childList target null// attributes child data-foo// There is no "attributes child data-bar" notification.

UsingattributeFilter

In this example, a Mutation Observer is set up to watch for changes to thestatus andusername attributes in any elements containedwithin a subtree that displays the names of users in a chat room. This lets the code,for example, reflect changes to users' nicknames, or to mark them as away from keyboard(AFK) or offline.

js
function callback(mutationList) {  mutationList.forEach((mutation) => {    switch (mutation.type) {      case "attributes":        switch (mutation.attributeName) {          case "status":            userStatusChanged(mutation.target.username, mutation.target.status);            break;          case "username":            usernameChanged(mutation.oldValue, mutation.target.username);            break;        }        break;    }  });}const userListElement = document.querySelector("#user-list");const observer = new MutationObserver(callback);observer.observe(userListElement, {  attributeFilter: ["status", "username"],  attributeOldValue: true,  subtree: true,});

Monitoring attribute values

In this example we observe an element for attribute value changes, and add a button which toggles the element'sdir attribute between"ltr" and"rtl". Inside the observer's callback, we log the old value of the attribute.

HTML

html
<button>Toggle direction</button><br /><div>  <input type="text" dir="ltr" value="Tofu" /></div><pre></pre>

CSS

css
body {  background-color: paleturquoise;}button,input,pre {  margin: 0.5rem;}

JavaScript

js
const toggle = document.querySelector("#toggle");const rhubarb = document.querySelector("#rhubarb");const observerTarget = document.querySelector("#container");const output = document.querySelector("#output");toggle.addEventListener("click", () => {  rhubarb.dir = rhubarb.dir === "ltr" ? "rtl" : "ltr";});const config = {  subtree: true,  attributeOldValue: true,};const callback = (mutationList) => {  for (const mutation of mutationList) {    if (mutation.type === "attributes") {      output.textContent = `The ${mutation.attributeName} attribute was modified from "${mutation.oldValue}".`;    }  }};const observer = new MutationObserver(callback);observer.observe(observerTarget, config);

Result

Specifications

Specification
DOM
# ref-for-dom-mutationobserver-observe②

Browser compatibility

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp