Click here to Skip to main content
15,889,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to set a href attribute to a variable. For example, if I had a variable called "link" that is equal to "main.html". Then, the href attribute would be equal to the variable "link", and when it was clicked, the person would go to "main.html". Then, if the variable was something else, it would be equal to that something else, such as "secondary.html".

What I have tried:

I tried using id="variable name" and href="variable name" and href=variable name.
Posted
Updated 4-Dec-20 6:40am

You can do it through javascript:

JavaScript
var myLink = document.getElementById("yourLinkId"); 
myLink.href = "some_url"

or you can use the setAttribute method:
JavaScript
var myLink = document.getElementById("yourLinkId");
myLink.setAttribute("href", "some_url");
 
Share this answer
 
Comments
AIDAN GREEN 4-Dec-20 10:19am    
I get that some_url represents the url that I Want it to be, but what does yourLinkId mean?
BabyYoda 4-Dec-20 10:41am    
the id of your anchor tag.

Somewhere you have something like < a id="myLink">Click to go to ...
I think your problem with this is more than just setting up that link.

Please go through this: HTML Tutorial[^]

and I strongly recommend this, as well JavaScript Tutorial[^]

I suggest this because your questions are of such an elementary nature that you seem to need a good solid (yet surprisingly quick and easy) walk through.
 
Share this answer
 

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