Add a Class to Body Tag: Testing Existing Javascript Solution with No Results

html, jquery

Solution

There's a couple minor issues with this code:

- Make sure the regex in `match` actually matches your URL patterns. I think Behance Prosites use a URL pattern like `/1234/section` and `/1234/5678/section/item`.

- The `match` function returns an array, so you can't pass `newClass` directly into `addClass`. You need to pass one of the array items, like `newClass[0]`.

- Since your script is in the `<head>` it can't modify `<body>` because it doesn't exist at execution time. You either need to move the script to the bottom of the page or defer execution until after the DOM is loaded.

This snippet should work specifically for Behance Prosites. The regex matches URL path segments with at least one non-numeric character, to filter out the `/1234/5678/` from the URL, so `newClass[0]` will be `section` in the above example URLs.

$(document).ready(function() {
  var path = window.location.pathname;
  var newClass = path.match(/[^\/]*[^\d\/][^\/]*/);
  $('body').addClass(newClass[0]);
});

Good luck!

Problem

I found a great piece of Javascript code (StackOverflow link: How to add a class to body tag?). However, I am having trouble implementing it. Below is the code I'm using on a test page: ``` <!doctype html> <html> <head> <title>Javascript Test</title> <meta charset="utf-8" /> <script type="text/javascript"> var newClass = window.location.href; newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/); $(document.body).addClass(newClass); </script> </head> <body> </body> </html> ``` However I do not see any class added to the body tag as a result. (Viewing Source in Safari, Chrome) I've tested with and without jQuery. Do you see what's wrong with the code? I'm working with a Behance ProSite. I can create multiple galleries, but each will have the same background because they use the same template. I need to add a unique class to the body tag so I can target each with a different CSS background property.

Original source

Related problems