Search code examples
javascriptmutation-observersmutation

How to grab class from mutations.target?


I am using this snippet of code below to log mutations.target.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    //console.log(mutations, observer);
    // ...
    
    mutations.forEach(function(mutation) {
        console.log(mutation.target);
    }); 
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
}); 

The specific element below (Example):

VM2246:9 <div id=​"1873868e7868ba9363aa46100a9cf976" class=​"tw-border-radius-medium tw-font-size-6 tw-inline-block tw-inline-tooltip tw-pd-05 tw-semibold" style=​"max-width:​ 300px;​">​380 cae-bucks​</div>​

So how do I grab the class name from mutations.target? Unfortunately the documentation is really bad.


Solution

  • You can just do:

    mutations[0].target.classList // this returns an array of all classes
    mutations[0].target.className // this returns a string containing all the classes separated with an space