Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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;
       }            
    })
})
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

contains is a method.

So you can't use: switch(size.classList.contains){case 'class1':...}

Instead you should use if(size.classList.contains('class1')){}

If you want a more clean code, you can create an array (or object) for the cases and put ifs on a loop.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!