Search code examples
javascriptdom-events

How do you do something if the DOM is changed?


How can I detect when the document changes?

I know I could do something like this:

var lastHTML = document.body.innerHTML;
setInterval(function() { if(document.body.innerHTML != lastHTML) { DOMupdated() } }, 500);

But is there an event handler I can put in place, like onchange?


Solution

  • There's the old DOM Mutation Events, and there's the new DOM Mutation Observers.


    For a quick overview of them both (and why the newer [more complex] API is better), check out this post:

    Detect DOM Changes with Mutation Observers.


    P.S. Don't miss the comments there...