Search code examples
javascriptmutation-observers

Javascript MutationObserver Error


The following script works, but chrome says that there is an error..
What should I do to solve this error?

function Do(){alert("test");}

new MutationObserver(Do).observe(document.body,{childList:true,subtree:true}); //works, but there's error.

The error message in chrome console is this;

Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist. (anonymous function)


Solution

  • The Node body has not been created when chrome executes the code. So you can change your code like this:

        window.onload=function(){
          function Do(){alert("test");};
          new MutationObserver(Do).observe(document.body,{childList:true,subtree:true});
        };
    

    or do with jQuery:

        $(document).ready(function(){
        //your code
        });