Search code examples
javascripthtmlsetintervalmutation-observers

Detecting class change without setInterval


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?


Solution

  • 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>