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

javascript - jQuery check if element has a class - Stack Overflow

programmeradmin5浏览0评论

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

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/9o70dbzz/2/

Share Improve this question edited Apr 19, 2016 at 22:12 Clomp 3,3082 gold badges24 silver badges38 bronze badges asked Apr 19, 2016 at 21:30 DejavuDejavu 7133 gold badges9 silver badges26 bronze badges 3
  • 3 Instead of switch statement use if else with hasClass() – emil.c 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? – Jeff Puckett Commented Apr 19, 2016 at 21:34
  • api.jquery./hasClass <--- The documentation is right there, free of charge, ready for you to read it. – Kevin B Commented Apr 19, 2016 at 21:45
Add a ment  | 

3 Answers 3

Reset to default 10

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/9o70dbzz/4/

发布评论

评论列表(0)

  1. 暂无评论