J82 J82 - 3 months ago 20
jQuery Question

Adding a body class based on url in address bar

Problem

I want to add

body
classes to two separate types of pages:

1) Pages that match this url:
example.com/shop/


2) Pages that have anything after
/shop/
in the url:
example.com/shop/asdfjkl, example.com/shop/item-2342, etc.





So far, I've solved the first problem by using this code:

if(window.location.href.match('example.com/shop/')){
jQuery('body').addClass('shop');
}


However, this also adds the
shop
class to any url that starts with
example.com/shop/
(refer to problem #2)




Question

How can I add a separate
shop-item
class to just the urls that have characters after
/shop/
?

Answer

You can use regex for that:

if( window.location.href.match.match(new RegExp('example.com/shop/.+')) ) {
    $('body').addClass('shop-item');
} else if (window.location.href.match('example.com/shop/')) {
    $('body').addClass('shop');
}
Comments