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?