Body Class JS

DescriptionJavascript snippet by - 10/06/10

This is an experimental technique to force a body class. If you are working with a system that does not allow you to use php this javascript solution will create a body class for you dynamically. It is experimental but will take the url and convert it to a css worthy string and use that for the class. It strips slashes and special characters. Put this snippet in the header file so it shows up for all pages.

Tags

<script type="text/javascript">
var currentUrl = location.pathname;
if(currentUrl == '/') document.body.setAttribute('class','home');
else{
	bodyClass = currentUrl.replace(/\//g,'');
	bodyClass = bodyClass.replace(/[^a-zA-Z 0-9 \-]+/g,'_');
	document.body.setAttribute('class',bodyClass);
}
</script>

<!-- This is a better version for BC -->

<script type="text/javascript">
var currentUrl = location.pathname;
if(currentUrl == '/') document.body.setAttribute('class','home');
else{
bodyClass = currentUrl.replace(/\//g,'');
bodyClass = bodyClass.replace('pages','');
bodyClass = bodyClass.replace('.html','');
bodyClass = bodyClass.toLowerCase();
bodyClass = bodyClass.replace(/[^a-zA-Z 0-9 \-]+/g,'_');
document.body.setAttribute('class',bodyClass);
}
</script>
  • Share
Authored by: Adam J Nowak
http://hyperspatial.com

Comments and Feedback