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="">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="">Get Started</a>

The expected result would yield the following embedded link:

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

What I have tried:

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.
Updated 3-Sep-21 6:17am

1 solution

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

<a href="" class="-js-referral-link">Get Started</a>

Then use querySelectorAll to find the links and update them:
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();

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