To change ALL links on the page, you can get the parameters coming from the URL with location.href
and extract only the string from ?
using the .substring()
method:
var url_ = location.href;
// url_ = https://meusite.com?utm_source=teste&utm_campaign=teste&utm_content=teste
var params = url_.substring(url_.indexOf("?"));
// params = ?utm_source=teste&utm_campaign=teste&utm_content=teste
Then just looping for all <a>
elements and concatenate the variable params
to the href
attribute of each:
// verifica se no params tem a string "?utm", caso contrário, não faz nada
if(~params.indexOf("?utm")){
var as = document.querySelectorAll("a");
for(var x=0; x<as.length; x++){
as[x].href = as[x].href+params;
}
}
Full Code:
// aguarda o DOM ser carregado
document.addEventListener("DOMContentLoaded", function(){
var url_ = location.href;
var params = url_.substring(url_.indexOf("?"));
if(~params.indexOf("?utm")){
var as = document.querySelectorAll("a");
for(var x=0; x<as.length; x++){
as[x].href = as[x].href+params;
}
}
});
Or, if you want only a few links to change, you need to identify them in some way. You can put class
, for example, class="alt"
:
<a class="alt" href="link">Link 1</a>
<br>
<a href="link">Link 2</a>
The code below will only change the links with the class .alt
, that is, the href
of the link 1
will be changed, but the link 2
will not:
document.addEventListener("DOMContentLoaded", function(){
var url_ = location.href;
var params = url_.substring(url_.indexOf("?"));
if(~params.indexOf("?utm")){
var as = document.querySelectorAll("a.alt");
for(var x=0; x<as.length; x++){
as[x].href = as[x].href+params;
}
}
});