最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Switch Statement and jQuery hasClass function - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked May 26, 2016 at 18:19 SuperTonySuperTony 692 silver badges8 bronze badges 4
  • Any reason you cannot just use if/else statements? – William Gates Commented May 26, 2016 at 18:22
  • The switch statement is used to pare two values. Since class can contain multiple values, you probably shouldn't be using switch. You'll probably need to grab all the classes and then use the if statement. – Erik Philips Commented May 26, 2016 at 18:22
  • $.hasClass is used to check if a specific element has a specific class. – IMTheNachoMan Commented May 26, 2016 at 19:44
  • I'm sorry, I meant to say that there is going to be places where the code looks like this: Switch() {} case '': case '': case '': case '': case '': case '': case '': I wanted to avoid the following type of if statements: if (body.hasClass('abc') || body.hasClass('abc') || body.hasClass('abc') || body.hasClass('abc') || body.hasClass('abc') || body.hasClass('abc')) { // some code } (Sorry: It appears the above examples are going to be a little tough to read without line breaks). – SuperTony Commented May 26, 2016 at 20:36
Add a ment  | 

5 Answers 5

Reset to default 5

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 */

I agree with the other answer that you're better suited to just use if, else if statements here, but an alternative would be to rip the classes off the body tag and check them against your strings:

var bodyClasses = ($('body').attr('class') || '').split(' ');

for (var i = 0, len = bodyClasses.length; i < len; i++) {
 switch(bodyClasses[i]) {
    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 know this is an old thread, but it may help someone else.

If you are able to ensure the classes for the element are declared in a specific order, you could ensure the class you are checking for is first / last in the list, and use something similar to this:

var bodyClass = $('body').attr('class');
var firstClass = bodyClass.slice(0, bodyClass.indexOf(' '));

switch(firstClass) {
    case 'homepage':
        // Some code here
        break;
    case 'residential-page':
        // Other code here
        break;
    default:
        // More code here
}

It's been a long time this has been asked. I will add my answer here as it might help others.

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

$(...).hasClass(...) returns true or false, not a string, so you can't use case "some string" within the switch statement - well, you can, but it will always result in the default action.

For the record: here is a non jQuery alternative. You can use the switch(true) pattern to be able to use any condition you need within the cases.

When you wrap the switch statement within a function, you can use return after a condition is met - so no break required there.

See also switch@MDN.

const body = document.querySelector(`#body4Test`);

console.log(bodyState(body.classList));

// let's test the other conditions
setTimeout(() => {
  body.classList.replace(`homepage`, `residential-page`);
  console.log(bodyState(body.classList));
  setTimeout(() => {
    body.classList.remove(`residential-page`);
    console.log(bodyState(body.classList));
  }, 1500);
}, 1500);


function bodyState(classList) {
  switch (true) {
    case classList.contains('homepage'):
      return "This is the homepage";
    case classList.contains('residential-page'):
      return "This is the residential page";
    default:
      return "default code block ran";
  }
}
#body4Test.homepage:before {
  content: "my class is "attr(class);
}

#body4Test.residential-page:before {
  content: "my class is "attr(class);
}

#body4Test:before {
  content: "they deprived me of classes";
}
<div id="body4Test" class="homepage"></div>

发布评论

评论列表(0)

  1. 暂无评论