I have following java script code:
var product = getQueryVariable("product");
$('a.link').each(function()
{
$(this).attr("href", $(this).attr("href") + "&product=" + getQueryVariable("product"));
});
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var variables = query.split("&");
for (var iCount = 0; iCount < variables.length; iCount++)
{
var pair = variables[iCount].split("=");
if (pair[0] == variable)
return pair[1];
}
}
If url is: http://www.xxxx.com/index.htm?product=abc
, It sets a link to an anchor tag
<a class="link" href="http://www.aaaa.com/index.htm">Click here</a>
as
<a class="link" href="http://www.aaaa.com/index.htm?product=abc">Click here</a>
which is what I want, and it does it well.
But if anchor tag already has product
variable in its href
like
<a class="link" href="http://www.aaaa.com/index.htm?product=xyz">Click here</a>
then I get
<a class="link" href="http://www.aaaa.com/index.htm?product=xyz&product=abc">Click here</a>
while I was expecting that if product
variable is present in href
of anchor tag, it will replace existing product variable. And if there is no product variable in href
tag, it will append it.
The code appends well, but does not replace existing product
variable in href
of anchor tag.
So, the question is how do I get 'product'
param from all a
tags that have class 'link'
? so that I can replace it in my code if found. And can I fetch it in $('a.link').each(function()
?
How can I do it?