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?
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".
To check if an element contains a class, you use the contains() method of the classList property of the element:*
Using Class. We can check for the existence of a class using Java Reflection, specifically Class. forName().
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With