Search code examples
jquerycssreplacestylesheet

use jQuery to replace a CSS stylesheet if body class changes


I have a stylesheet in my head as follows:

<link rel="stylesheet" href="/templates/jooswatch-v3-5/css/bootswatch/superhero/bootstrap.min.css">

I am trying to replace the above stylesheet with the follow ones if the body#main.whatever class changes (on different pages for example).

i.e.

changing from: body#main.itemid113

to: body#main.itemid114

<script>
jQuery(document).ready(function() {

   $('body#main.itemid113').replaceWith('<link rel="stylesheet" id="main" href="/templates/jooswatch-v3-5/css/bootswatch/cerulean/bootstrap.min.css" type="text/css" />');

   $('body#main.itemid114').replaceWith('<link rel="stylesheet" id="main" href="/templates/jooswatch-v3-5/css/bootswatch/cosmo/bootstrap.min.css" type="text/css" />');

});
</script>

How would I do this - the above is not working.

Would this be correct?

jQuery(function($){
    if ($('.itemid113').length){
        $('body').append("<link rel="stylesheet" href="/templates/jooswatch-v3-5/css/bootswatch/cerulean/bootstrap.min.css" type="text/css" />");
    };
    if ($('.itemid114').length){
        $('body').append("<link rel="stylesheet" href="/templates/jooswatch-v3-5/css/bootswatch/cosmo/bootstrap.min.css");
    }
});

Solution

  • The easiest way to accomplish this is to add an id to your link tag i.e.:

    <link id="theme" rel="stylesheet" href="/templates/jooswatch-v3-5/css/bootswatch/superhero/bootstrap.min.css">
    

    Then your script becomes:

    jQuery(function($){
        if ($('.itemid113').length){
            $('#theme').attr("href","/templates/jooswatch-v3-5/css/bootswatch/cerulean/bootstrap.min.css");
        };
        if ($('.itemid114').length){
            $('#theme').attr("href", "/templates/jooswatch-v3-5/css/bootswatch/cosmo/bootstrap.min.css");
        }
    });