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
Jake Lett is a results-driven B2B marketing consultant with 15+ years of experience helping businesses boost online visibility, generate qualified leads, and increase sales. Specializing in SEO, HubSpot, and PPC campaign management, Jake leverages proven strategies to deliver measurable growth. As a Certified Google Ads Specialist and HubSpot Developer, he is committed to driving impactful results for his clients.

Related posts

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter