Question

I want to use javascript or jquery to add a class to an object based on the URL query string.

So if the url is example.com/?var=1 then I want to add a new class to the object #mydiv

This would then be repeated for ?var=2, ?var=3 and so on.

Here is what I have tried. The hope for this is that it would add a different class to the object if the query string was either ?var=2 or?var=3

var queryString = window.location.search.substr(1); 

switch (queryString) {
    case "2": document.getElementById('mydiv').className = 'newclass2';
;
                   break;
    case "3": document.getElementById('mydiv').className = 'newclass2';
;
                     break;
  }

EDIT:

It almost works now....

Here is my current code:

<script>
 var queryString = window.location.search.substr(1);
 var variant = queryString.split('=')[1];
 switch(variant) {
    case "stnl2": document.getElementById('getexclusive-sb').className = 'stnlvar2';
;
break;
    case "stnl3": document.getElementById('getexclusive-sb').className = 'stnlvar3';
;
break;
  }
</script>

It works if the url is "/?v=stnl2"

However Google content adds more to the url such as "?v=stnl2&utm_expid=42387987-0.dmsadhasjkdjasgdjgas-Q.4"

Is there a way for me to ignore the & and all details after so my code still works?

Was it helpful?

Solution

var getUrlVars = function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if(vars[0] == window.location.href){
        vars =[];
    }
    return vars;
}
var params = getUrlVars();
switch (params['var']){
...
}

Your params will have all the parameters from your query string. just past the variable name as a string and you will get the value of that parameter.

OTHER TIPS

The solution you tried has two issues.

First, you are getting the number of variant incorrectly. With your code, queryString will be like "var=2". So if you want only number, you should also split it by =:

 var queryString = window.location.search.substr(1);
 var variant = queryString.split('=')[1];
 switch(variant) {
     // ...
 }

Note that this still actually doesn't check the name of your parameter, i.e. var=. If it is the only parameter, it would work. Otherwise, for proper handling of query string in JS you might want to look at this question

Second, look attentively into your switch. Both branches are actually identical, so they would do exactly the same regardless of queryString. Seems like you copy-pasted it unintentionally.

UPD:

As a said in my original answer, I just pointed you to some issues in your solution and how to fix them. It would not work if there is more than one parameter. Of course, you can just ignore all the string after &. But still there would be many cases in which it still won't work: what if your parameter is not the first?

I think it is not a good idea to make such assumptions, so we come to what I said previously: you might need proper, full-fledged parsing of parameters. The link that I mentioned provides A LOT of solutions for this particular task, you may choose any of them. Another option is to use some existing library which have such function provided. That question and some other SO questions pointed me to these two:

  • jquery.parsequery — a jQuery plugin for this only purpose, with which you can do variant = $.query(location).get("paramName"). Seems to be old and not updated.
  • jsurl — a library for making different things with URLs, in particular, you can do variant = (new Url).query.paramName with it.

NB: (replace paramName with your actual parameter name, v or var or whatever)

Of course there could be some other good libs for it, also try googling on your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top