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

Hi Friends!

I just coded a custom Cookie Banner which I like to integrate into a Wordpress website. I use the custom HTML CSS and JS Snippets to integrate the code into Wordpress.

When I tested the Cookie Banner in VSCode everything worked fine, but when I integrate the code into Wordpress, I get the following error:

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

The Cookie Popup doesn´t show up because the JS file does not get exectued. Probably beacuse reading ‘AddEventListener’ is null and the code stops running there?

Can someone help me with this please??

This is the JS code:

let cookieModal = document.querySelector('.cookie-consent-modal');
let cancelCookieBtn = document.querySelector('.btn.cancel');
let acceptCookieBtn = document.querySelector('.btn.accept');

cancelCookieBtn.addEventListener('click', function () {
  cookieModal.classList.remove('active');
  console.log('Tracking code is NOT running!');
});

acceptCookieBtn.addEventListener('click', function () {
  cookieModal.classList.remove('active');
  localStorage.setItem('cookieAccepted', 'yes');
  useGA();
  console.log('GA Code is running!2');
  useFP();
  console.log('FP Code is running!2');
});

setTimeout(function () {
  let cookieAccepted = localStorage.getItem('cookieAccepted');
  if (cookieAccepted != 'yes') {
    cookieModal.classList.add('active');
  }
}, 2000);

let cookieAccepted = localStorage.getItem('cookieAccepted');
if (cookieAccepted == 'yes') {
}

// Run Google Analytics Code

function useGA() {
  ***GOOGLE ANALYTICS CODE***
  console.log('GA Code is running!1');
}

// Run Facebook Pixel Code

function useFP() {
 ***FACEBOOK FIXEL CODE***
  console.log('FP Code is running!1');
}

What did I do wrong??

Have you checked if thats a typo in the class you re trying to select?

What do you mean by that? A type error? Yes I checked it, but I couldn´t find an issue and the wired thing is that everything runs smoothly from VS Code, just Wordpress gives back this error message…

Either cancelCookieBtn or acceptCookieBtn is null (probably both). That means that those elements doesn’t exist in the scope.
If it’s not a typo in the class name(s) my next guess would be that either JS or HTML are in an iframe.

check you HTML classes… you might have mispelled something …

When does the script load?

Try wrapping the code inside a DOMContentLoaded event handler to make sure the DOM is ready before querying for elements.

document.addEventListener("DOMContentLoaded", () => {
  // your code
});
1 Like

Thanks everyone for your help!

The JS file loaded before the HTML file., so the AddEventListerner could not find the class and throiw the error…

@lasjorg Thank you, this is a good way to test if it is because of loading issues.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.