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 B2B marketing consultant with over 15 years of experience in the digital marketing industry. He specializes in SEO, HubSpot, and PPC campaign management. Jake has a proven track record of helping businesses increase their online visibility and drive more traffic, leads and sales. He is a Certified Google Ads Specialist and a Certified HubSpot Developer.

Topic:

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter