0

Is there a function to detect if a new element injection has been made to the DOM? Instead of constantly checking after my ajax call to see if there's new images injected like so:

$.ajax({
    ...
    ...
    success: function(data) {
        $('.content').replaceWith(data);
        if ($(data).find('img').length) alert('New images found!');
    }
});

I was hoping there's a function out there that exists to check if new images was added to the DOM. Example:

$('img').injected(function() {
    console.log('Found new images: ' + this);
});
user1105430
  • 1,379
  • 3
  • 15
  • 27

1 Answers1

0

You can detect DOM changes trough mutation observers. As I do not know your markup I'll go with a generic elements. .injectedElementParent is the parent where you want to inject the img.

// select the target node
var target = document.querySelector('.injectedElementParent');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation);
    });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }

// pass in the target node, as well as the observer options
observer.observe(target, config);  
Mircea
  • 11,373
  • 26
  • 64
  • 95