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 =;
      if ((!mutation.oldValue || !mutation.oldValue.match(/\bis-busy\b/)) 
        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



Related Questions

Sponsored Content

22 Answered Questions

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

30 Answered Questions

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

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2510562 View
  • 2682 Score
  • 30 Answer
  • Tags:   javascript html dom

7 Answered Questions

[SOLVED] Detect changes in the DOM

11 Answered Questions

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

16 Answered Questions

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

1 Answered Questions

[SOLVED] MutationObserver for class (not for id)

4 Answered Questions

[SOLVED] jQuery selector: Firefox recognize but IE not

Sponsored Content