5

i am using mutationObserver to detect changes using bellow code

var target = document.querySelector('body');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

in this i am able to detect changes if changes happen inside the targeted element right now i am targeting body

what i exactly want is the mutationObserver event only fires when the element i had specified is added to the DOM

Ashish Patel
  • 921
  • 1
  • 10
  • 26
  • Why don't play with a `onload` event on your specified element ? – Steeve Pitis Feb 23 '17 at 13:56
  • 1
    Examples: [Observe mutations on a target node that doesn't exist yet](//stackoverflow.com/a/38882022) or [How to change the HTML content as it's loading on the page](//stackoverflow.com/a/39334319) or [this one](//stackoverflow.com/a/41797066) or use a library/wrapper, there many. – wOxxOm Feb 23 '17 at 14:43

1 Answers1

-2

You can have a good example of Mutation Observer on this page:

http://www.htmlgoodies.com/beyond/javascript/respond-to-dom-changes-with-mutation-observers.html

The working example add the observer on the body, and if you add, remove, or change an attribute you can capture the change.

But to be sure that all things are well capture use this observerConfig.

            var observerConfig = {
                    attributes: true,
                    childList: true,
                    characterData: true,
                    subtree : true
            };
Shaan1974
  • 65
  • 1
  • 4
  • This is essentially a link-only answer that doesn't contain relevant information in the answer itself. – wOxxOm Feb 23 '17 at 14:45
  • This example is a real good piece of code. You have just to add "subtree" as true in the observerConfig. This example explain also that it's better to target the document in place of the body tag. – Shaan1974 Feb 27 '17 at 12:54
  • The answer itself doesn't explain that you need to check each node in addedNodes of each mutation to find the one you're looking for. The link in the answer isn't needed for that. – wOxxOm Feb 27 '17 at 12:57
  • You could briefly explain the example in the link and include more of its contents here. This way the context of the answer will remain here and not rely on the external link to be available. – Bojidar Stanchev Aug 06 '19 at 13:59