randC
randC

Reputation: 1

Javascript check if target contains class with switch-case instead of if else

Currently I have a code structure:

if(target.classList.contains('animate-heading')){

}else if(target.classList.contains('animate-text')){

}else if(target.classList.contains('animate-buttons')){

}else if(target.classList.contains('image-rotating-animation')){

}else if(target.classList.contains('plans-heading-animation')){

}else if(target.classList.contains('plans-animation')){

}else if(target.classList.contains('animate-masonry')){

}

which I want to replace with switch-case statements, is it possible to do it? Thanks in advance!

Upvotes: 0

Views: 306

Answers (1)

epascarello
epascarello

Reputation: 207527

Switch checks for an exact match so there is nothing you really could do to match it. You could do it as a truthy check in a switch, but it does not make it any cleaner than the if/else if

const classList = target.classList

switch (true) {
  case classList.contains('animate-heading'):
  break;
  case classList.contains('animate-text'):
  break;
} 

Upvotes: 1

Related Questions