Is there a jquery event that fires when a new node is inserted into the dom?

deprecated: as per @Meglio’s comment below, the DOMNodeInserted event is deprecated, and will be removed from the web at some unkown time in the future. For the best results, start learning about the MutationObserver API.

see @dain’s answer below.

If you bind the ‘DOMNodeInserted’ event to the document or body directly, it will get executed every time anything is inserted anywhere. If you want the callback to run only when a particular kind of element is added, you would be wise to use delegated events.

Usually, if you are adding a class of elements to the DOM you will be adding them to a common parent. So attach the event handler like this:

$('body').on('DOMNodeInserted', '#common-parent', function(e) {
  if ($(e.target).attr('class') === 'myClass') {
    console.log('hit');
  }
});

Basically the same answer as Myke’s above, but since you are using a delegated event handler rather than a direct event handler, the code in there will be fired less often.

NOTE:

$('body').on('DOMNodeInserted', '.myClass', function(e) {
  console.log(e.target);
});

This seems to work too… but I don’t know why.

Leave a Comment