Class change detection without setInterval

I have a div that adds extra classes to it programmatically. How can I detect a class name change without using this implementation of setInterval ?

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

MutationObserver?

+5
source share
1 answer

You can use the mutational observer . This is pretty widely supported now.

 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> 
+6
source

Source: https://habr.com/ru/post/1263986/


All Articles