Add class to body element based on string in URL

// JavaScript, jQuery

What it does

In this example, we will add a class to the body element if it ends with the string /colours/.

The Code

$j=jQuery.noConflict();                        // jQuery noConflict mode

$j(document).ready(function() {        // Initialise when the DOM is ready

    if (window.location.href.indexOf("/colours/") > -1) { // If the last part of the url is '/colours/'
        $j('body').addClass('colourPage');    // Add body class
    } else {
        $j('body').addClass('otherPage');        // Otherwise, add a different class


How To Use It

Paste this snippet into a JavaScript file that is loaded by your page, or you can put it between <script> </script> tags in the footer.

jQuery is required.