Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a switch statement in jQuery/Javascript to test if an element has a particular class?

This is the structure of the if-else statement I am using:

$('.myclass a').click(function() {
   if ($(this).hasClass('class1')) {
        //do something
   } else if ($(this).hasClass('class2')) {
        //do something
   } else if ($(this).hasClass('class3')) {
        //do something
   } else if ($(this).hasClass('class4')) {
        //do something
   } else {
        //do something
   }
});

There are quite a number of cases already and I thought using a switch statement would be neater. How do I do it in jQuery/javascript?

like image 326
catandmouse Avatar asked Sep 15 '11 15:09

catandmouse


People also ask

How do you check if an element has a specific class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

How do you check if an element has a specific class in JavaScript?

To check if an element contains a class, you use the contains() method of the classList property of the element:*

How do you find whether a class is present or not?

Using Class. We can check for the existence of a class using Java Reflection, specifically Class. forName().

Can switch statement use conditions?

switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. The switch statement is closely related to a conditional statement containing many else if blocks, and they can often be used interchangeably.


1 Answers

Try this. Not much cleaner, but still a switch statement.

$('.myclass a').click(function() {
    switch (true) {
      case $(this).hasClass('class1'):
        // do stuff
        break;
      case $(this).hasClass('class2'):
        // do stuff
        break;
      case $(this).hasClass('class3'):
        // do stuff
        break;
    }
}
like image 117
Xyan Ewing Avatar answered Oct 26 '22 15:10

Xyan Ewing