javascriptattributesevent-handlingcustom-events

JavaScript: Listen for attribute change?


Is it possible in JavaScript to listen for a change of attribute value? For example:

var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);

element.setAttribute('something','whatever');

function doit() {

}

I would like to respond to any change in the something attribute.

I have read up on the MutationObserver object, as well as alternatives to that (including the one which uses animation events). As far as I can tell, they are about changes to the actual DOM. I’m more interested in attribute changes to a particular DOM element, so I don’t think that’s it. Certainly in my experimenting it doesn’t seem to work.

I would like to do this without jQuery.

Thanks


Solution

  • You need MutationObserver, Here in snippet I have used setTimeout to simulate modifying attribute

    var element = document.querySelector('#test');
    setTimeout(function() {
      element.setAttribute('data-text', 'whatever');
    }, 5000)
    
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.type === "attributes") {
          console.log("attributes changed");
    
          // Example of accessing the element for which 
          // event was triggered
          mutation.target.textContent = "Attribute of the element changed";
        }
        
        console.log(mutation.target);
      });
    });
    
    observer.observe(element, {
      attributes: true //configure it to listen to attribute changes
    });
    <div id="test">Dummy Text</div>

    Additionally, mutation.target property gives the reference to mutated/changed node.