Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  38] [ 5]  / answers: 1 / hits: 21568  / 7 Years ago, thu, february 23, 2017, 12:00:00

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?


More From » javascript

 Answers
21

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')
}

[#58802] Tuesday, February 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
juancarlos

Total Points: 580
Total Questions: 105
Total Answers: 103

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
;