1
2

More than 3 years have passed since last update.

JQueryの代わりに MutationObserver を使って子要素の追加を検知したい

Last updated at Posted at 2020-01-23

書いてみたコード

function printEl(el, indent = "") {
    console.error(indent + "tag=" + el.tagName + " ,id=" + el.id + " ,class="+ el.className);
    el.childNodes.forEach((child) => {
        printEl(child, indent + "  ");
    });
}

function watchChildElementAdditions(target){
    if ( target == null || typeof(target) == "undefined") {
        console.error("監視するノードが指定されていません");
        return;
    }

    // オブザーバインスタンスを作成
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if ( mutation.type != "childList" ) {
                return;
            }
            mutation.addedNodes.forEach( el => {
                printEl(el);
            });
        });
    });

    // 対象ノードとオブザーバの設定を渡す
    observer.observe(target, {
        attributes: false,
        characterData: false,
        childList: true,
        subtree: true,
    });
}

watchChildElementAdditions(document.getElementById('target-id'));

やっていること

MutationObserver で対象ノードの子孫も含めて監視します。子孫のノードが追加されると、 MutationObserver のコンストラクタに指定したコールバックが呼ばれ、 MutationRecordが引数で渡されます。これの addedNodes プロパティに追加された子ノードがあるので、childNodes で子孫を探していきます。

addedNodes 追加されたノードの最上位の親が渡されます。

1
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
1
2