Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't do with Switch-Case what I do with If-Else in JS?

Can you help about the JS DOM example below,

The if-else structure I specified in example 1 works, but the switch-case structure I specified in example 2 does not work. The switch-case structure does not work, although they both function the same. Why ?

Thanks

--- Example 1 / Works ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
        if(size.classList.contains('font-size-1')) {
            .....
        } else if (size.classList.contains('font-size-2')) {
            .....   
        }
        
    })
})

--- Example 2 / Doesn't work ---

fontSizes.forEach(size => {
 
    size.addEventListener('click', () => {
      
      switch (size.classList.contains) {
           case 'font-size-1': 
             ....
           break;
           case 'font-size-2': 
             ....
           break;
       }            
    })
})
like image 425
Hasan Hamit Avatar asked Dec 30 '25 19:12

Hasan Hamit


2 Answers

Please not that they are not the same. In the first one you are calling function add taking the output whereas in the second one all you are passing via switch statement is the reference to function. The size.classlist.contains is a function which expects an argument. Please know the difference.

like image 184
Suhail Akhtar Avatar answered Jan 01 '26 11:01

Suhail Akhtar


You didn't use the switch properly, you're checking size.classList.contains which points to a function with strings (like font-size-1) instead of comparing the actual value.

You can use split (with the includes functions) or use size.classList.contains in each case

Take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains How to check className in a switch statement when an element has multiple classes

like image 45
Ron Hillel Avatar answered Jan 01 '26 11:01

Ron Hillel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!