118

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

Barry Chapman
  • 6,690
  • 3
  • 36
  • 64
Manngo
  • 14,066
  • 10
  • 88
  • 110
  • 3
    `MutationObserver` works for that. Just configure it to listen to attribute changes. Set it to observe only the element you’re interested in. – Sebastian Simon Jan 02 '17 at 10:27

2 Answers2

201

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.

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Thanks for the answer and for the sample. Once I have streamlined this, I think it will be good technique for making more complex changes to elements by simply changing and attribute. It makes an easier API. Would you be aware of a reasonable polyfill for primitive browsers? – Manngo Jan 02 '17 at 10:44
  • @Manngo, For primitive browsers you can use [Mutation events](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events) and also see https://davidwalsh.name/dom-events-javascript – Satpal Jan 02 '17 at 10:46
  • I see that it is currently supported back to IE9, and still supported in modern browsers. Thanks again. – Manngo Jan 02 '17 at 10:49
  • kinda useless when we have no access to the element in the observer – inux Dec 03 '22 at 17:11
10

This question is already answered, but I'd like to share my experiences, because the mutation observer did not bring me the insights in needed.

Note This is some kind of hacky solution, but for (at least) debugging purposes quite good.

You can override the setAttribute function of a particalar element. This way you can also print the callstack, and get an insight of "who" changed the attribute value:

// select the target element
const target = document.querySelector("#element");
// store the original setAttribute reference
const setAttribute = target.setAttribute;
// override setAttribte
target.setAttribute = (key: string, value: string) => {
  console.trace("--trace");
  // use call, to set the context and prevent illegal invocation errors
  setAttribute.call(target, key, value); 
};
scipper
  • 2,944
  • 3
  • 22
  • 45