36

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?

0

7 Answers 7

56

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
3
  • 7
    more effective than $('body') is $(document.body), avoids the selector process. See jsperf.com/jquery-body-vs-document-body-selector (note: 'higher is better' in given stats)
    – Frank N
    Mar 18, 2013 at 12:47
  • $(document.body) works with jQuery 1.9.0 as well (while $("body") doesn't work (tested in Chrome)). Apr 18, 2013 at 20:54
  • Oh thank you I was trying to do that and it wasn't working but you saved me :)
    – Jerome
    Apr 27, 2017 at 9:32
22

Use:

$(document.body).addClass('about');
4
$('body').toggleClass("className");

perfectly works

1
  • While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
    – hellow
    Nov 12, 2018 at 8:14
3

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);
0
1

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 :)

-2

Something like this might work:

$("body").attr("class", "about");

It uses jQuery's attr() to add the class 'about' to the body.

1
  • This works fine for adding a class to the body. Just didn't answer the question.
    – iCode
    Aug 30, 2016 at 16:19
-3

I had the same problem,

<body id="body">

Add an ID tag to the body:

$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.

Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.