Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Uncaught TypeError: Cannot read property 'classList' of null

Tags:

javascript

How do I check if the element I am clicking on has a classlist?

let dropdown  = target.nextElementSibling.classList.contains('form__select-dropdown')

My code is erroring on this line when the element that I click on doesn't have a class attached to it.

Which makes complete sense.

However I only want the below code to run if the nextElementSibling has the class form__select-dropdown:

        if (!selectTag && dropdown) {
            target.querySelector('.form__select-dropdown').classList.remove('active')
        } else {
            target.nextElementSibling.classList.toggle('active')
        }

So I need to check if the target.nextElementSibling.classList exists before I do my condition to avoid the error but I'm unsure how to do this?

like image 476
Max Lynn Avatar asked Sep 05 '25 02:09

Max Lynn


1 Answers

Your issue is that target doesn't always have a nextElementSibling; you should check if it is null before proceeding.

let next = target.nextElementSibling
let dropdown = next && next.classList.contains('form__select-dropdown')

And later in your code:

    if (!selectTag && dropdown) {
        target.querySelector('.form__select-dropdown').classList.remove('active')
    } else {
        next && next.classList.toggle('active')
    }
like image 77
gyre Avatar answered Sep 07 '25 16:09

gyre