How Can I Add a Class to the Body Tag using jQuery?

10,593

Not sure what your restrictions are in placing code. I would just put this in the <head> of your document and apply the class to the html element instead of body so you don't get a FOUS or "Flash of Unstyled Content". The class is "present" on the element almost immediately after the page loads, but before it displays if you do it this way:

<script type="text/javascript">
    var loc = window.location.pathname.match(/^\/?(\w+)\b/);
    // document.documentElement is the html element, this adds the class
    if(loc) document.documentElement.className += " " + loc[1].toLowerCase();
</script>

If you really want to use jQuery:

<script type="text/javascript">
    // jQuery is passed to the ready function as a parameter, so we alias it with $
    // This will work for you even with wikispaces
    jQuery(function($){
        var loc = window.location.pathname.match(/^\/?(\w+)\b/);
        if(loc) $(document.body).addClass(loc[1].toLowerCase());
    });
</script>
Share:
10,593
Spencer B.
Author by

Spencer B.

Updated on June 26, 2022

Comments

  • Spencer B.
    Spencer B. almost 2 years

    Let me clarify my question, and the solution I'm looking for. I'm using wikispaces.com, and I would like to dynamically add a unique body class for every page using jQuery that somehow grabs the URL, and then inserts that unique body class that would be applied specifically and only for that page.

    So, here's an example url from my wikispace...

    http://wikithemes.wikispaces.com/Audio+Page

    I'd like the jQuery to grab... let's say the first word after the .com/, which on this page would be audio. So, the jQuery I need would apply the class audio to the body tag, like so...

    <body class="audio">
    

    In their documentation, any jQuery can be inserted since it is loaded by default. But they clarify in saying that instead of the $ sign used within jQuery, it will only work within wikispaces if you use the word jQuery instead. Like this...

    jQuery(document).ready(function(){
    

    I really appreciate any help you can give me on getting this to work. Thanks!