Add class to body based on the URL – jQuery


// find the pathname
var urlPath = window.location.pathname;
//convert to lowercase
urlPath.match(//(.*?)(+|$)/)[1].toLowerCase();
// remove the first character
urlPath = urlPath.replace(///g, '-').slice(1);
//remove file extension
urlPath = urlPath.replace(/.[^/.]+$/, "");
// add class to body
$(document.body).addClass(urlPath);
// If body has no class its propably the homepage
$('body:not([class])').addClass('home');

 



Written by: Jake Lett
I share digital marketing tips and HubSpot tutorials to help marketers and business owners grow their business.

Topic:

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter