如何从mutations.target中获取类?

问题描述

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

那么我该如何从mutation.target获取类名?不幸的是,文档真的很糟糕。

解决方法

您可以这样做:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...