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');

 


About the Author

Jake Lett is a results-driven Detroit based B2B marketing consultant with 15+ years of hands-on experience managing SEO and PPC campaigns across manufacturing, SaaS, and professional services industries. He’s a Certified Google Ads Specialist and HubSpot CMS Developer who has personally managed budgets ranging from $500 to over $10,000/month.

Jake specializes in helping small businesses and solo marketers get more from lean ad budgets—using practical strategies that drive qualified leads, not just traffic. He shares real-world lessons on his blog, YouTube channel, and in his published books on digital marketing.



Related posts

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter