如何从mutations.target中抓取class?

How to grab class from mutations.target?

我正在使用下面的这段代码来记录 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
  //...
}); 

下面的具体元素(例子):

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>​

那么如何从 mutations.target 中获取 class 名称?不幸的是文档真的很糟糕。

你可以这样做:

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