如何在 childList 突变上使用 .contains?

How to use .contains on childList mutation?

我正在使用 MutationObserver 并想检查 target.className 上的 class 选择器,但出现错误

Cannot read properties of undefined (reading 'contains')

所以我查看了 classList 的原型,它有 .contains 方法,我做了以下 target.classList.prototype.contains("OverlayWrapper") 但我仍然得到同样的错误。

我不明白为什么我在尝试检查部分 className 时收到此错误。

编辑:我添加了控制台的快照

编辑:我已经为代码做了一个示例,这是我正在寻找包含 popUp__wrapper 的 class 添加到 DOM 的最低限度。 (当我们按下打开按钮时,控制台会报错)jsfiddle

问题

  • mutation.addedNodes 是一个 nodeList(节点集合)。所以很明显classList里面不存在

  • 您的 class popUp__wrapper 后缀为 scxdxcfd。没有 class 确切的名字 popUp__wrapper.

解决方案

let wrapperEl = Array.from(mutation.addedNodes) // convert NodeList to array
      .filter(n => n.nodeType != Node.TEXT_NODE) // remove text nodes
      .find(n => n.matches('[class*=popUp__wrapper]')) // search for class

如果您需要检查节点内可用的 popUp__wrapper,请使用 querySelector 而不是 matches

演示

https://jsfiddle.net/aswinkumar863/qjeafxd8/20/

参考资料

https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

https://developer.mozilla.org/en-US/docs/Web/API/Text