You always need to "catch" the most restrictive case first. So change your logic to:
if (node.hasClass("a") && node.hasClass("b")){
//do something
}else if(node.hasClass("a")){
//do something different
}else{
//some something else all together
};
Question
I have 3 possible class combinations that can be applied to an element, for our sake the classes are
".a" and ".b"
sometimes both .a
and .b
can be applied or sometimes just .a
and sometimes no classes at all. I want to write an if statement that catches all 3 possible combinations for example
if (node.hasClass("a")){
//do something
}else if(node.hasClass("a") && node.hasClass("b")){
//do something different
}else{
//some something else all together
};
But right now this if statement is not working, any suggestions?
Thanks!
** hasClass(); is a YUI3 method
Solution
You always need to "catch" the most restrictive case first. So change your logic to:
if (node.hasClass("a") && node.hasClass("b")){
//do something
}else if(node.hasClass("a")){
//do something different
}else{
//some something else all together
};
OTHER TIPS
Your original code doesn't work because if the node has class a
(regardless of whether or not it also has class b
), it will enter the first block, and never check the other conditions.
Try this instead:
if (node.hasClass("a")) {
if(node.hasClass("b")) {
// has a and b
} else {
// has a only
}
} else {
// does not have a
};
if(node.hasClass("a") && node.hasClass("b"))
{
//both .a and .b
}
else if(node.hasClass("a"))
{
//only .a
}
else if(node.hasClass("b"))
{
//only .b
}
else
{
//neither
}