Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
David Avatar asked Feb 08 '17 19:02

David


1 Answers

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>
like image 113
motanelu Avatar answered Sep 18 '22 14:09

motanelu