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?
The body_class() function in WordPress makes this very easy for us by automatically adding a bunch of appropriate classes to the body tag of our website. One such example would be the logged-in class that is added to the body tag if a logged-in user is viewing the page.
Tip: The class attribute can be used on any HTML element. Note: The class name is case sensitive!
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
: hasIf 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