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.
Use the classList. add() method to add a class to the body element, e.g. document. body. classList.
Using . add() method: This method is used to add a class name to the selected element. Syntax: element.
To add a class to the body tag, you can do the following in vanilla Javascript without the need to include some fat 3rd party library
If a class already exists on the body then
document.body.className += " something";
Otherwise
document.body.className = "something";
Example on jsfiddle
To have the class added after the page has finished loading then use addEventListener and create a handler for the window.onload event
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
window.addEventListener("load", function () {
document.body.className = "something";
}, false);
There's a couple minor issues with this code:
match
actually matches your URL patterns. I think Behance Prosites use a URL pattern like /1234/section
and /1234/5678/section/item
.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]
.<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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With