Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if element has a class

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/

like image 692
Dejavu Avatar asked Jan 31 '26 21:01

Dejavu


2 Answers

Use the .hasClass() function.

if($("body").hasClass("page1")){
  $("h1").html("heading1");
}
else if($("body").hasClass("page2"){
  $("h1").html("heading2");
}
else {
  $("h1").html("default");
}
like image 83
Sonny Avatar answered Feb 02 '26 09:02

Sonny


This can be solved with selectors:

$('h1').html('default');
$('body.page1 h1').html('heading1');
$('body.page2 h1').html('heading2');
like image 37
GG. Avatar answered Feb 02 '26 10:02

GG.