Click here to Skip to main content
15,075,638 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a page which has 6 identical links that depends on referralTokenValue to track clicks from site A to B.

The link uses the following link structure:
<a href="https://example.com/program?referralToken=123456789">Get Started</a>


Because of the number of link in the page, I'm looking for simple Javascript, without any dependencies on external CDN library(ies), where I can add the referralToken value to the Href tag, like so:

var referralTokenValue = 123456789

<a href="https://example.com/program?referralToken=referralTokenValue">Get Started</a>


The expected result would yield the following embedded link:
https://example.com/program?referralToken=12345789


How can add the referralTokenValue to the link without the use of the ID attribute?

What I have tried:

Quote:
I also have a running prototype at: JSFiddle - Code Playground[^]

However, I can't use this prototype because it uses ID as an attribute in the link, and it would cause an issue with 6 identical links.
Posted
Updated 3-Sep-21 6:17am
v2

1 solution

Drop the referral token from the links. Add some means of identifying the links from Javascript.

Eg:
HTML
<a href="http://example.com/program" class="-js-referral-link">Get Started</a>

Then use querySelectorAll to find the links and update them:
JavaScript
const referralTokenValue = 123456789;
const referralLinks = document.querySelectorAll("a.-js-referral-link");
for (let a of referralLinks){
    const url = new URL(a.href);
    url.searchParams.set("referralToken", referralTokenValue);
    a.href = url.toString();
}
Demo[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900