shonen.hateblo.jp

やったこと,しらべたことを書く.

htmlの要素の変化を検知する

jQuery中.

個人的な事情で必要になったので,簡単に調べた.

やりたいこと

javascriptによって,htmlのdomの構造が書き換えられたとき,それを検知したい.

結論

MutationObserverというものがあるので,これを使う.

developer.mozilla.org

(new MutationObserver(()=>{ console.log("detected!"); }))
    .observe(document.documentElement, { childList: true, attributes: true, subtree: true });

document.documentElement の子要素に変化があったとき,{ console.log("detected!"); } を実行する. documentElementとは,documentのルート要素

上のコードを実行した後,コンソールに下のコードを打ち込んでみると,detected!と表示されるはず.

document.documentElement.append(document.createElement("span"));

詳細

コールバック関数の引数から,どのノードが変化したか,何が変化した(子が追加削除された?属性が変更された?)か等の情報が得られる.

function callback(mutationList, observer) {
  for (let m of mutationList) {
    console.log("type", m.type);
    console.log("target", m.target);
  }
}

(new MutationObserver(callback))
    .observe(document.documentElement, { childList: true, attributes: true, subtree: true });