0

I am trying to add a class to the body depending on the url querystring (or hash if thats easier)

If you go to http://www.here.com?myclass I want to page to change the class of the body to: <body class="myclass">

This is the closest I got using a hash:

$(document).ready(function() {

    var url=document.URL.split('#')[1];
    if(url == undefined){
        url = '';
    }

    if(url != ''){
        $(document.body).addClass('myclass');
    }
});
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
JP Myrtle
  • 1
  • 2
  • This tells how to get the query: http://stackoverflow.com/questions/16901981/add-hash-before-location-pathname/16902458#16902458 – Lee Meador Jul 24 '13 at 20:25

3 Answers3

0

Your code is close:

var url=document.location

or

var url=document.location.hash
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

I always like it when I can find the answer here so i will paste it in.

This code of ther is a hash in the url http://www.domain.com# Adds a class of "myclass" to the body tag. Note it ADDS the class not replaces.

$(document).ready(function() {

var url=document.location.hash;
if(url != ''){
    $(document.body).addClass('myclass');
}

});

JP Myrtle
  • 1
  • 2
0

Since you know the query string you want to have add the class, this should work:

$(function() {
   if (document.location.href.indexOf('?myclass') > -1 ) {
     $('body').addClass('myclass');
   } 
});

Search strings using > -1 or >= 0 to avoid errors.

JGV
  • 5,037
  • 9
  • 50
  • 94
RoJenkz
  • 1
  • 2