LoginSignup
0
2

More than 1 year has passed since last update.

MutationObserverで要素を監視

Posted at

MutationObserverとは?

MutationObserverはDOMの変化を監視することができます。

// 変更を監視するノードを取得
const targetNode = document.getElementById('targetId');

// オブザーバーのオプション
const config = { attributes: true, childList: true, subtree: true };

// MutationObserverオブジェクトを生成
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        // 変更があった時の処理
        console.log(mutation.type);
    }
};

// 監視をスタート
observer.observe(targetNode, config);

// 監視を停止したい時
observer.disconnect();

オブザーバーのオプション

  • childList - 要素の子要素
  • subtree - 要素の全ての子孫に対する変更
  • attributes - 要素の属性の変更
  • attributeFilter - 指定したものだけを監視するため
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2