LoginSignup
17
17

More than 5 years have passed since last update.

子要素が追加されたことを検知して処理を行う

Posted at

ある要素になにかしら子要素が追加された場合に処理をしたいことがある。

<div class='any-element'>
  <div class='child'>子要素</div>
</div>

イベント

DOM4 Events以降に対応しているブラウザであれば、MutationObserverを使用すれば良いが、それ以前のブラウザではDOMNodeInsertedイベントにフックする方法がある。
(IEだと11以上からMutationObserverを使える)
https://developer.mozilla.org/ja/docs/Web/API/MutationObserver

if (typeof MutationObserver !== 'undefined') {
  var mo = new MutationObserver(function(mutations) {
    $.each(mutations, function(i, mutation) {
      var target = $(mutation.target);
      // hogehoge
    });
  });
  $.each($('.any-element').get(), function(index, elem) {
    mo.observe(elem, {childList: true});
  });
} else {
  $('.any-element').bind('DOMNodeInserted', function(event) {
    var target = $(this);
    // hogehoge
  });
}

ポーリング

その他にも、子要素を追加するタイミングで親要素に unread のようなクラスを付与する、という前提で、下記のようにポーリングすることもできる。
※複数の子要素を同時に追加する、というケースだと重複して処理しないよう制御が必要

$('input[type=file]').on('change', function() {
  var interval = setInterval(function () {
    var target = $('.any-element');
    if (target.length > 0 && target.hasClass('unread')) {
      // hogehoge
      target.removeClass('unread');
      clearInterval(interval);
    }
  }, 100);
});
17
17
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
17
17