Consider I have a JavaScript variable named link
which contains a URL like this: www.google.com
. I need to include this variable in href
attribute in 2 places, like:
<a href="link">link</a>
This should return something like this: Google
I tried various ways but failed. Is it possible to do like this? The JavaScript variables should be used at both places.
Note:
I need to use the variable inside <a>
tag also
href”, append the variable to it (Here we have used a variable named “XYZ”). Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named 'XYZ' and its value is 55.
In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).
The only way to pass data with an anchor tag is to put them in the query string.
To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value. For example, let's say we are creating links for each store and manager.
Assume you have the following in your HTML
<a href="link" class='dynamicLink'>link</a>
<a href="link" class='dynamicLink'>link</a>
You can do the following
var href = 'http://www.google.com'; //any other link as wish
var links = document.getElementsByClassName('dynamicLink');
Array.from(links).forEach(link => {
link.href = href;
link.innerHTML = href.replace('http://', '');
});
JSFiddle
You can use the following code.
<a id="myLink" href="link">link</a>
in your javascript try
<script>
var link = "http://www.google.com/";
document.getElementById('myLink').setAttribute("href",link);
document.getElementById('myLink').innerHTML = link;
// Here the link is your javascript variable that contains the url.
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With