How can ı prevent the console error?

I’m making a pop-up menu and the code works properly, but when I touch an element outside of the class I want to find in the code below, the console fails. How can I prevent this?

footerWrapper.addEventListener('click', showFooter)

function showFooter(e) {
    let target =
    if (target.classList.contains('footer__list')) {
// Error
Uncaught TypeError: can't access property "classList", target is null

Well, do you understand what the error is telling you? It is saying that target is null so it has no properties. No primitive has properties, but null and undefined will through errors (because they have no object wrapper).

So do you want to prevent the error or fix it? To prevent it, you’d have to dig in deeper to the code and see what is causing to be null. As a first step, I’d do a console.log(; at the top of that function.

By the way, I think “target” is a bad name for your variable.

If this is working the way you want and just prevent this error, there are various approaches.

You could default the class list:

let target = || { classList: [] }

You could do a return early pattern:

function showFooter(e) {
    let target =
    if (!target) {
    // ...

You could do some short-circuit protection:

if (target && target.classList.contains('footer__list'))
// or
if (target && target.classList && target.classList.contains('footer__list'))

or if you have access to optional chaining:

if (target?.classList.contains('footer__list'))
// or
if (target?.classList?.contains('footer__list'))
1 Like

Thanks I have already tried some of the methods you posted. Strangely, when I do a “target === null” query, it doesn’t return a boolean value.

Strangely, when I do a “target === null” query, it doesn’t return a boolean value.

Wait, what? That doesn’t make sense. If it’s JS, then an expression with the === operator should always return a value. That e object may be weird because it is a system event, but an expression with an operator like === is always either true or false, afaik. There are no other possibilities. They either contain the exact same value or they don’t.

I’m sorry I wrote it wrong. I said it means True is not turning

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