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 = e.target.nextElementSibling
if (target.classList.contains('footer__list')) {
target.classList.toggle('visible')
}
}
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 e.target.nextElementSibling to be null. As a first step, I’d do a console.log(e.target); 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 = e.target.nextElementSibling || { classList: [] }
You could do a return early pattern:
function showFooter(e) {
let target = e.target.nextElementSibling
if (!target) {
return
}
// ...
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'))
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.