0

I am using MutationObserver and want to check a class selector on target.className but I get an error

Cannot read properties of undefined (reading 'contains')

so I looked at classList's prototype and it has .contains method and I did the following target.classList.prototype.contains("OverlayWrapper") and I still get the same error.

I don't understand why I am getting this error as I am trying to check for a partial className .

Edit: I have added a snapshot of the consoleenter image description here

Edit: I have made an example for the code, it is the bare minimum where I am looking for a class that contains popUp__wrapper being added to the DOM. (an error will be in the console when we press the open button) jsfiddle

localhost
  • 822
  • 2
  • 20
  • 51
  • 1
    You need to show an actual [MCVE](/help/mcve) that demonstrates the problem. Right now it looks like your `target` is not an element, but just a plain text `Node`. – wOxxOm Apr 14 '22 at 11:59
  • 1
    As others have indicated, please post actual code the reproduces the issue so we may best assist you here. not just a picture of some code – Mark Schultheiss Apr 14 '22 at 13:07
  • @wOxxOm I have posted an example of code that demonstrates the problem. – localhost Apr 17 '22 at 13:12

1 Answers1

1

Issues

  • mutation.addedNodes is an nodeList (collection of nodes). So obviously classList not exists in it.

  • Your class popUp__wrapper is suffixed with a an scxdxcfd. No class with exact name popUp__wrapper.

Solution

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

If you need to check popUp__wrapper available inside the node, use querySelector instead of matches

Demo

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

References

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

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

User863
  • 19,346
  • 2
  • 17
  • 41
  • This is great. I have some questions. why use a filter? and how do we know if the array has any method on it from just console? – localhost Apr 22 '22 at 14:15
  • 1
    The filter is used to omit the [text nodes](https://stackoverflow.com/questions/17195868/what-is-a-text-node-its-uses-document-createtextnode), we want only the element nodes. And yes, the console is the best option to learn new methods or you can also use [mdn docs](https://developer.mozilla.org/en-US/) – User863 Apr 22 '22 at 15:07