Dejavu
Dejavu

Reputation: 711

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/

Upvotes: 2

Views: 12627

Answers (3)

GG.
GG.

Reputation: 21894

This can be solved with selectors:

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

Upvotes: 4

Nevermind
Nevermind

Reputation: 21

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/

Upvotes: 1

Sonny
Sonny

Reputation: 303

Use the .hasClass() function.

if($("body").hasClass("page1")){
  $("h1").html("heading1");
}
else if($("body").hasClass("page2"){
  $("h1").html("heading2");
}
else {
  $("h1").html("default");
}

Upvotes: 10

Related Questions