0

I've been recently trying to build a WordPress based website, and I added few JavaScripts modules to it and they all worked fine until today. I have no idea how it happened or how to solve it. I get an error reading:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

My code:

class MobileMenu {
  constructor() {
    this.menu = document.querySelector(".site-header__menu")
    this.openButton = document.querySelector(".site-header__menu-trigger")
    this.events()
  }

  events() {
    this.openButton.addEventListener("click", () => this.openMenu())
  }

  openMenu() {
    this.openButton.classList.toggle("fa-bars")
    this.openButton.classList.toggle("fa-window-close")
    this.menu.classList.toggle("site-header__menu--active")
  }
}

export default MobileMenu

Screenshot of the error: Screenshot of the broswer console displaying the error message

I'd appreciate any help at this point, I'm fairly a beginner and I couldn't find any solution for the past few hours. Thanks!

cabrerahector
  • 3,653
  • 4
  • 16
  • 27
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Ivar Aug 08 '22 at 14:51
  • This will happen in two cases, if there are `site-header__menu-trigger` class or the script executed before the dom loaded. – Mina Aug 08 '22 at 14:51
  • Have a quick read of this: https://www.w3schools.com/whatis/whatis_htmldom.asp More often than not this type of error is caused by trying to reference an element before it has been loaded by the browser. There is a clearly defined hierarchy of how a browser loads a web page and it can be easy to be caught out. Once you read the hierarchy of how the page loads it will be fairly easy to ensure that any elements required are loaded before trying to access them. – arresteddevelopment Aug 08 '22 at 15:05

0 Answers0