How to determine if mutation has been called?

Tags: , ,



I have this mutation observer function below. The issue is that if the condition is met for “false” that console.log will log many times in the browser. I think the best way to fix this is to add something in here that if the mutation is met don’t run function.

Does adding in mutationObserver.disconnect(); after the else if condition the best way to accomplish this?

            window.addEventListener('DOMContentLoaded', (event) => {
            
            // Listening to Class Changes //
            var mutationObserver = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    var change = mutation.target.classList.contains('hidden-class');
                    if (change === true) {
                        return true;
                    }
                    else if (change === false) {
                        console.log('this mutation is visible');
                        }
                });
            })
            mutationObserver.observe(document.getElementById('cart-wrapper'), {
                attributes: true,
                characterData: true,
                childList: true,
                subtree: true,
                attributeOldValue: true,
                characterDataOldValue: true
            });

        });

Answer

Use .some instead, to iterate over the mutations and see if any of the targets’ classLists contain the class:

var mutationObserver = new MutationObserver(function (mutations) {
  const somethingJustMutatedIsHidden = mutations.some(
    mutation => mutation.target.classList.contains('hidden-class')
  );
  if (somethingJustMutatedIsHidden) {
    // do something?
  } else {
    console.log('this mutation is visible');
  }
})

Keep in mind that forEach ignores its return value; the return true you currently have doesn’t do anything.



Source: stackoverflow