Detecting class change without setInterval

David picture David · Feb 8, 2017 · Viewed 13.4k times · Source

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?

Answer

motanelu picture motanelu · Feb 8, 2017

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>