user2347736 user2347736 - 2 years ago 90
CSS Question

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

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>
<title>Javascript Test</title>
<meta charset="utf-8" />

<script type="text/javascript">
var newClass = window.location.href;
newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);


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.

I am sure I am missing something elementary because I'm a beginner with Javascript. Do you see what's wrong with the code?

More Background:
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.

Answer Source

There's a couple minor issues with this code:

  1. 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.
  2. 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].
  3. 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\/][^\/]*/);

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download