Reputation: 61
I'm new to writing my own javascript, but have successfully used a url parameter to add CSS and a class to my page (thanks to great answers on stackoverflow). However, next, I need to append the same url parameter to all links on the page, such that if a user clicks on a link, the same parameter goes on to the next page:
<script type="text/javascript">
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
if (getQueryVariable("code")=="awesome"){
document.getElementById("copy").style.color="blue";
document.getElementById("coupon_code").className = "plug_coupon";
};
What I need:
if (getQueryVariable("code")=="awesome"){
append ?code=awesome to the href - how to do?
};
</script>
Thanks!
P.S. Even better would be to append only if the links contain my domain, not if the links are going outside my site (an ad, for example).
Upvotes: 0
Views: 183
Reputation: 7884
If you can't use jQuery try a while loop:
var p = 'myURLParameter';
var i = 0, t;
while(document.body.getElementsByTagName('a') [i++]) {
t = this.getAttribute("href");
this.href = t + "?parameter=" + p;
}
Upvotes: 0
Reputation: 2934
Select all your links and then loop through them like this (uses jQuery):
$('a').each(function() {
$(this).attr('href', this.href + myVar);
});
If you want to check for only your domain:
var comp = new RegExp(location.host);
$('a').each(function() {
if(comp.test($(this).attr('href'))){
$(this).attr('href', this.href + myVar);
}
});
Upvotes: 2