Search code examples
javascriptjqueryswitch-statement

Switch Statement and jQuery hasClass function


I am trying to use a switch statement to check if the current page has a specific body class. This is kind of what I am looking for:

var bodyClass = $('body').hasClass('className')

 switch(bodyClass) {
    case 'homepage':
        // console.log("This is the homepage");
        break;
    case 'residential-page':
        // console.log("This is the residential page");
        break;
     default:
     // console.log("default code block ran");
 }

I do understand that the jQuery hasClass function returns true of false and is used like $('body').hasClass('someClassName') and this will return true or false. Also, my body typically has about 7-10 different class names for a given page.


Solution

  • This is not the use case for a switch in my opinion, but a simple set of branches

    var body = $('body');
    
    if(body.hasClass('abc')) {
    }
    else if(body.hasClass('def')) {
    }
    else {
      /* default case */
    }
    
    /* etc */