Detecting class change without setInterval

2020-02-11 18:30发布

问题:

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?

回答1:

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>