首页 > 解决方案 > 通过 MutationObserver 遍历多个 addedNodes 并获取 target.innerText

问题描述

我正在处理每秒添加多个节点以及删除多个节点的页面。但我只对新添加的节点和其中的文本感兴趣。这是我的脚本

let mList = document.querySelector('._24tx'),
  options = {
    childList: true,
    attributes: false,
    characterData: true,
    subtree: true,
    attributeOldValue: false,
    characterDataOldValue: true
  },
  observer = new MutationObserver(mCallback);

function mCallback(mutations) {
  mutations.forEach(function (mutation) {
      if (mutation.addedNodes.length > 0) {
        for (var i = 0; i < mutation.addedNodes.length; i++) {
          if (mutation.target.innerText != '') {
            console.log(mutation.target.innerText);       
          }
        }
      }
    }
  );
}

observer.observe(mList, options); 

我收到单个节点的重复条目。如何定位每个addedNodes并获取它们的innerText?

标签: javascriptnode.jsdommutation-observers

解决方案


推荐阅读