J82 J82 - 2 months ago 8
jQuery Question

Adding classes to 'body' with JavaScript

I'm trying to add classes to the

body
of certain pages. All of the classes get added except for the 2nd, 3rd, and 4th if statements, as labeled below. I'm thinking perhaps it's because of the ordering of the if statements? I'm not sure. Can someone help me out?

if (window.location.href.match(/\/shop\/\?category/)) {
jQuery('body').addClass('shop-category');
} else if (window.location.href.match(/\/shop\/\?category=Chef/)) { //doesn't get added
jQuery('body').addClass('shop-category-chef');
} else if (window.location.href.match(/\/shop\/\?category=Tactical/)) { //doesn't get added
jQuery('body').addClass('shop-category-tactical');
} else if (window.location.href.match(/\/shop\/\?category=Tools/)) { //doesn't get added
jQuery('body').addClass('shop-category-tools');
} else if (window.location.href.match(new RegExp('/shop/.+')) ) {
jQuery('body').addClass('shop-item');
} else if (window.location.href.match('/shop/')) {
jQuery('body').addClass('shop');
}

Answer

The order is the problem. ?category matches before ?category=Chef. Just change the order.

if (window.location.href.match(/\/shop\/\?category=Chef/)) {
  jQuery('body').addClass('shop-category-chef');
} else if (window.location.href.match(/\/shop\/\?category=Tactical/)) {
  jQuery('body').addClass('shop-category-tactical');
} else if (window.location.href.match(/\/shop\/\?category=Tools/)) {
  jQuery('body').addClass('shop-category-tools');
} else if (window.location.href.match(/\/shop\/\?category/)) {
  jQuery('body').addClass('shop-category');
} else if (window.location.href.match(new RegExp('/shop/.+'))) {
  jQuery('body').addClass('shop-item');
} else if (window.location.href.match('/shop/')) {
  jQuery('body').addClass('shop');
}
Comments