2

I am trying to check to see if an HTML element has a class and if so, then run a function with jQuery. My code only works if an element doesn't have multiple classes. I believe I need to use the .hasClass() method, but I couldn't figure it out.

var pageClass = $("body").attr('class');
switch (pageClass) {
  case ("page1"):
    $('h1').html('heading1');
    break;
  case ("page2"):
     $('h1').html('heading2');
    break;
  default:
    $('h1').html('default');
}

fiddle: https://jsfiddle.net/9o70dbzz/2/

3
  • 3
    Instead of switch statement use if else with hasClass() Commented Apr 19, 2016 at 21:33
  • 1
    what would you do if the body had all 3 classes? would you only want the first, or last, or append all together? Commented Apr 19, 2016 at 21:34
  • api.jquery.com/hasClass <--- The documentation is right there, free of charge, ready for you to read it. Commented Apr 19, 2016 at 21:45

3 Answers 3

10

Use the .hasClass() function.

if($("body").hasClass("page1")){
  $("h1").html("heading1");
}
else if($("body").hasClass("page2"){
  $("h1").html("heading2");
}
else {
  $("h1").html("default");
}
Sign up to request clarification or add additional context in comments.

3 Comments

is the only way is to use if else statement?
Using if/else with the "hasClass" function is the easiest way. Using a switch statement would be too convoluted in this scenario.
What Sonny says makes sense, as the code examples use multiple classes. The .hasClass() method is similar to if (className.indexOf('page1') > -1) { ... }. Neither one of those works well in a switch. However, you could use unique id attributes with a switch. Like: <body id="page1"> or <body id="page2"> & then use switch($("body").attr("id")) {...}. The reason is that only 1 value is passed into the switch with the id, rather than multiple values with the classes. So it's good to remember that switches work with single value keys & if/else statements work with multiple input keys.
4

This can be solved with selectors:

$('h1').html('default');
$('body.page1 h1').html('heading1');
$('body.page2 h1').html('heading2');

Comments

1

I would do it in such way....

$(document).ready(function() {
var element = $("body");

var classesCollection = {
    'page1': 'heading1',
    'page2': 'heading2'
};

for (var propertyName in classesCollection) {
    var propertyValue = classesCollection[propertyName];
    if (element.hasClass(propertyName)) element.html(propertyValue);
    else element.html('default');
}

});

https://jsfiddle.net/9o70dbzz/4/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.