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/
Use the .hasClass() function.
if($("body").hasClass("page1")){
$("h1").html("heading1");
}
else if($("body").hasClass("page2"){
$("h1").html("heading2");
}
else {
$("h1").html("default");
}
This can be solved with selectors:
$('h1').html('default');
$('body.page1 h1').html('heading1');
$('body.page2 h1').html('heading2');
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