Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class to body tag?

Tags:

jquery

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?

like image 884
shin Avatar asked Aug 16 '09 05:08

shin


People also ask

How do I add a class to the body tag in WordPress?

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.

Can we use class with body in HTML?

Tip: The class attribute can be used on any HTML element. Note: The class name is case sensitive!


1 Answers

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
like image 89
Rex M Avatar answered Sep 22 '22 12:09

Rex M