简体   繁体   中英

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/

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');

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM