Pat McInnes
Pat McInnes

Reputation: 65

Dynamic Hyperlink in HTML

I need to create a hyperlink that will change each day to incorporate the date from the day previous

Example:

For a download link on May 16th

<a href="http://www.example.com/dir/download-2020-05-15" title="Download Link">Download</a>

For a download link on May 17th

<a href="http://www.example.com/dir/download-2020-05-16" title="Download Link">Download</a>

I understand that there would probably be some script that can do this for me, but I cannot find it. Sorry if I am repeating other questions here.

Upvotes: 1

Views: 7557

Answers (2)

Preeti A.
Preeti A.

Reputation: 159

@PatMcInnes : you can create 3 different elements of a tag like this :

var elementCreatedOne = document.getElementById("a1”);

var elementCreatedTwo = document.getElementById("a2”);
var elementCreatedThree = document.getElementById("a3”);

var todaysDate = new Date();
var formattedDate= todaysDate.getFullYear() + '-' + (todaysDate.getMonth() + 1) + '-' + todaysDate.getDate();


elementCreatedOne .setAttribute("href", 
    “Link1” + formattedDate);

elementCreatedTwo .setAttribute("href", 
    “Link2” + formattedDate);

elementCreatedThree .setAttribute("href", 
    “Link3” + formattedDate);

HTML :

<a href="" id="a1” title="Download Link">Download</a>
<a href="" id="a2” title="Download Link">Download</a>
<a href="" id="a3” title="Download Link">Download</a>

Upvotes: 1

Romeo Dabok
Romeo Dabok

Reputation: 51

I'm still kinda new to js but I hope this helps...

<!-- The download link in which we shall change its target URL -->
<a id="downloadLink" href="#">Download</a>

<!-- Javascript script changing the link with the id "downloadLink" target URL  -->
<script type="text/javascript">
//The first part of the link without the date
var download = "http://www.example.com/dir/download-";

//Gets the link element in which the target URL will be changed
var link = document.getElementById("downloadLink");

//Gets the current date and formats it as yyyy-mm-dd
var cd = new Date().toISOString().slice(0,10); 

//Finally we change the links "href" attribute so it will now include the first part of the download link and date 
link.href = download + cd;
</script>

Upvotes: 0

Related Questions