I think you're asking for code that will extract the "filename" portion of the url path, and set that as a class name on the body element.
If so, then here's the basic idea:
$(document).ready(function() {
var parts = window.location.pathname.split('/');
var basename = "default-no-basename";
if( parts && parts.length ) {
var idx = parts.length-1;
if( parts[idx] == '' && parts.length > 1 ) {
--idx;
}
basename = parts[idx];
}
//alert("basename: "+basename);
$(body).addClass( basename );
});
That code simply extracts the portion of the page url following the final slash, and writes it into the class
attribute of the body tag. If the url path is a "directory" (ie. it ends with a slash), then it'll use the trailing directory name instead. If the url path is just '/', then it'll default to adding the classname 'default-no-basename'
.
Important: The above code does not do anything to ensure that the classname is compliant with the allowed characters in css classnames. So if your url was something like: http://example.com/abc/my-cool-page(with stuff).html
, then you're going to have problems, because the css class will be set to "my-cool-page(with stuff).html"
.
You would therefore want to either ensure that this is never being called on a page that has special chars (like (
, )
, .
, and the [space] character in the above example). Or you'll want to add some checking in to that logic to strip out disallowed chars.
good luck.