By sliptype


2018-03-09 20:53:35 8 Comments

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

0 comments

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] Detect changes in the DOM

18 Answered Questions

[SOLVED] How to get a JavaScript object's class?

  • 2009-08-08 18:11:57
  • DNB5brims
  • 714847 View
  • 764 Score
  • 18 Answer
  • Tags:   javascript oop

17 Answered Questions

[SOLVED] Change the selected value of a drop-down list with jQuery

25 Answered Questions

[SOLVED] How do I add a class to a given element?

2 Answered Questions

[SOLVED] Detect scrollHeight change with MutationObserver?

  • 2017-06-08 06:38:46
  • Thorsten Westheider
  • 1833 View
  • 10 Score
  • 2 Answer
  • Tags:   mutation-observers

12 Answered Questions

[SOLVED] How to change the href for a hyperlink using jQuery

16 Answered Questions

[SOLVED] Changing the image source using jQuery

32 Answered Questions

[SOLVED] How can I change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2667915 View
  • 2842 Score
  • 32 Answer
  • Tags:   javascript html dom

4 Answered Questions

[SOLVED] jQuery selector: Firefox recognize but IE not

Sponsored Content