33

I have a div that has additional classes added to it programmatically. How can I detect the class name change without using this setInterval implementation?

setInterval(function() {
    var elem = document.getElementsByClassName('original')[0];
    if (elem.classList.contains("added")) { detected(); }
}, 5500);

MutationObserver?

mm8
  • 163,881
  • 10
  • 57
  • 88
David
  • 13,619
  • 15
  • 45
  • 51
  • 1
    Can you fire an event when you change the class? Or do you want to detect the class change on a client that isn't doing the changing? ie. the document has changed? You may be able to do that with a push update. – Jon Glazer Feb 08 '17 at 19:07
  • 3
    This is what MutationObserver with attributeFilter option is for: [How to react to a specific style attribute change with mutation observers?](//stackoverflow.com/a/39024295) - replace `style` with `class`. – wOxxOm Feb 08 '17 at 19:11
  • I'm not doing the changing... My code is injected via chrome extension – David Feb 08 '17 at 19:11
  • Possible duplicate of [Is there a JavaScript/jQuery DOM change listener?](https://stackoverflow.com/questions/2844565/is-there-a-javascript-jquery-dom-change-listener) – bdkopen Aug 30 '17 at 00:01

1 Answers1

53

You can use a mutation observer. It's quite widely supported nowadays.

var e = document.getElementById('test')
var observer = new MutationObserver(function (event) {
  console.log(event)   
})

observer.observe(e, {
  attributes: true, 
  attributeFilter: ['class'],
  childList: false, 
  characterData: false
})

setTimeout(function () {
  e.className = 'hello'
}, 1000)
<div id="test">
</div>
motanelu
  • 3,945
  • 1
  • 14
  • 21