MutationObserver class changes

冷暖自知 提交于 2019-12-01 02:43:50

问题


I am using MutationObserver to detect when a specific class has been added to an element.

const observer = new MutationObserver((mutations) => { 
    mutations.forEach((mutation) => {
      const el = mutation.target;
      if ((!mutation.oldValue || !mutation.oldValue.match(/\bis-busy\b/)) 
        && mutation.target.classList 
        && mutation.target.classList.contains('is-busy')){
        alert('is-busy class added');
      }
    });
 });

observer.observe(document.querySelector('div'), { 
  attributes: true, 
  attributeOldValue: true, 
  attributeFilter: ['class'] 
});

My question is: Is there a better way to verify that this is a newly added class? Currently I am using regex to check that the class didn't exist previously and classList to check that the class exists now. Seems messy

Fiddle

来源:https://stackoverflow.com/questions/49201984/mutationobserver-class-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!