I want to add a class to a body tag with jQuery.
For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case 'about', to the body tag:
<body class="about">
How can I do that?
I want to add a class to a body tag with jQuery.
For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case 'about', to the body tag:
<body class="about">
How can I do that?
This should do it:
var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);
The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:
newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);
That pattern should yield the following:
../about_us.html
: about../something.html
: something./has_two_underscores.html
: has$('body').toggleClass("className");
perfectly works
You can extract that part of the URL using a simple regular expression:
var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);
Well, you're going to want document.location
. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then
$(body).addClass(foo);
I know this isn't the complete answer, but I assume you can work the rest out :)
Something like this might work:
$("body").attr("class", "about");
It uses jQuery's attr()
to add the class 'about' to the body.