I’m adding classes
to specific pages based on slug.
To make it more manageable, I’ve sorted of these pages into an array
called darkThemePages
.
However, one of the groups of pages I’m targeting are blog level 2 pages. The main blog sits on /insights
. However, what I’m trying to target are all pages under this blog (i.e. /insights/*
).
However, I can’t see a way to target all pages under certain slugs and if it’s possible to keep it in an array?
My approach:
var currentPageURL = window.location.pathname.replace(//+$/, '');
var root = document.getElementsByTagName('html')[0];
var className = "theme--dark";
var darkThemePages = ['/insights/*', '/terms-and-conditions'];
if (darkThemePages.indexOf(currentPageURL) > -1) {
root.classList.add(className);
} else{
root.classList.remove(className);
}
Advertisement
Answer
You can test if a regular expression matches the pathname of the current URL, and then add/remove the class from the root element accordingly:
const root = document.documentElement;
const url = new URL(window.location.href);
const className = 'theme--dark';
const regexp = /^/insights/.+|^/terms-and-conditions$/;
root.classList[regexp.test(url.pathname) ? 'add' : 'remove'](className);
Here are some tests to show examples of what kinds of url pathnames would/wouldn’t match the regular expression:
const regexp = /^/insights/.+|^/terms-and-conditions$/;
for (const pathname of [
'/insights',
'/insights/',
'/insights/post1',
'/insights/post2',
'/insights/post1/ok',
'/about',
'/terms-and-conditions',
'/terms-and-conditions/',
'/terms-and-conditions/etc',
'/terms-and-conditions-and-more',
]) {
const matched = regexp.test(pathname) ? '✅' : '❌';
console.log(matched, pathname);
}
And here’s a page that explains the regular expression, character by character (you can learn more there and modify/experiment as well): https://regexr.com/75plc