A Simple Script to Add Body Classes Based on Path Names in Squarespace

 

It’s always annoyed me that Squarespace doesn’t give you much page to page specificity. Clients often want to have more of a variety in different sections of their site. You can use the page ids to target specific page styles, but that’s not ideal for a couple of reasons:

  1. It’s hard for you to read in your custom CSS.

  2. It’s specific to only 1 page

  3. If, for some reason, you ever need to replace that page with another page, that specific id will change

A solution? Use this super quick and easy Javascript snippet to add body class names to your Squarespace site. It will separate out the words that follow the ‘/’ off your main site url.

Here’s an example: You have a separate page system of pages under About and you want to control the styling of the heading on that page. The url is https://yoursite.com/about/meet-our-team. Adding this snippet to the footer would add the classes `about` to the body class list to target that series of pages in the custom CSS section.


Here’s how it works!

Copy this code snippet:

<script>
const path = window.location.pathname.split( '/' )[1];
document.body.classList.add(path);
</script>

Go to Footer in Advanced > Code Injection > Footer.

Paste the code snippet!

Whew, that was easy! Now you can use that class for styling.


This is perfect for targeting product pages or landing pages as a whole category. You can right click on the page and inspect with your developer tools to make sure it’s working. Body classes will get appended to the end of the class list, so they will appear near the bottom of that huge list of classes.


Need even more classes?

You can use this snippet to add the full path as separate classes:

<script>
const path = window.location.pathname.split( '/' );
path.shift();
document.body.classList.add(...path);
</script>

Ex. That url from our previous example: https://yoursite.com/about/meet-our-team would add classes `about` AND `meet-our-team` to the body element.


Boom! Now you are done and you can go forth with more readable CSS and an easy way to style specific systems of pages.

 
A Simple Script to Add Body Classes Based on Path Names in Squarespace