We would like to introduce a feature that dynamically adds a page-specific CSS class to the <body> element based on the content of the main <h2> heading.
Description
The script reads the text content of the first <h2> element on the page, converts it into a URL-friendly “slug,” and appends it as a class to the <body> element in the format:
page-{slug}
Example
If the <h2> contains:
“About Us”
The following class would be added to <body>:
page-about-us
Key Behavior
- Converts heading text to lowercase
- Replaces Scandinavian characters (ä, ö, å) with ASCII equivalents
- Removes special characters
- Replaces whitespace with hyphens
- Prevents duplicate hyphens
- Applies the class only if valid text exists
Dynamic Content Support
The feature also observes DOM changes using MutationObserver to ensure the class is added even if the <h2> element is loaded asynchronously.
Benefits
- Enables page-specific styling without manual class assignment
- Improves maintainability and consistency across pages
- Works automatically with dynamically loaded content
Proposed Implementation
// Add a class to the page.
(function () {
function slugify(text) {
return text
.toLowerCase()
.trim()
// Scandinavian characters → ASCII
.replace(/ä/g, "a")
.replace(/ö/g, "o")
.replace(/å/g, "a")
// remove special characters
.replace(/[^a-z0-9\s-]/g, "")
// whitespace → dash
.replace(/\s+/g, "-")
// remove duplicates
.replace(/-+/g, "-");
}
function setPageClass() {
const h2 = document.querySelector("h2");
if (!h2) return;
const text = h2.textContent || "";
if (!text.trim()) return;
const slug = slugify(text);
if (slug) {
document.body.classList.add(`page-${slug}`);
}
}
// run immediately
setPageClass();
// if content loads later
const observer = new MutationObserver(() => {
if (!document.body.className.includes("page-")) {
setPageClass();
}
});
observer.observe(document.body, { childList: true, subtree: true });
})();
Why this is needed
At the moment its very hard to add CSS to specific pages since everything is done with Tailwind and has no classes. Note that I have already implemented this my self in my scripts, but this should be a native feature to ensure better CSS implementation.