Categories
Javascript

How to listen to changes in the DOM – An intro to Mutation Observer

Today I faced an issue in one of the developments I work on. We have a form with an input radio and, for some reason, one of the choices was disabled.

I inspected the source html to check if the disabled attribute was being set from the server but it wasn’t. At this point I knew that some JS was causing the issue but, how to determine which script was doing that.

Mutation Observer to the rescue:

The MutationObserver is part of the Web Api of the DOM.

It has very good support fot the majority of browsers, see: canIuse.

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

How to listen to the changes made to an element?

var element = document.querySelector('#myId');
    setTimeout(function() {
        element.setAttribute('data-text', 'whatever');
    }, 5000)

var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type == "attributes" && mutation.attributeName === 'disabled') {
                console.log("attributes changed", mutation);debugger;
            }
        });
    });

    observer.observe(element, {
        attributes: true //configure it to listen to attribute changes
    });

The snipped above will make the debugger to stop just after the change is made.

Once you are in the debugger you can see the callstack and see the chain of events that triggered the change.

I was able to find the solution.

I hope this helps someone else.