Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript variable inside an anchor tag's href attribute

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

like image 721
user3678812 Avatar asked May 27 '14 07:05

user3678812


People also ask

How do you add a variable inside a href?

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.

Can you put JavaScript in href?

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).

Can we pass value in anchor tag?

The only way to pass data with an anchor tag is to put them in the query string.

How do I add a variable to a URL?

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.


2 Answers

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

like image 122
T J Avatar answered Nov 15 '22 12:11

T J


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>
like image 22
Radhakrishna Rayidi Avatar answered Nov 15 '22 12:11

Radhakrishna Rayidi