user3678812
user3678812

Reputation: 447

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

Upvotes: 9

Views: 25478

Answers (5)

T J
T J

Reputation: 43156

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

Upvotes: 8

Radhakrishna Rayidi
Radhakrishna Rayidi

Reputation: 520

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>

Upvotes: 6

Hamster
Hamster

Reputation: 680

You can do this easy by jquery.

1st give your a class/id.

<a class="mylink">link</a>

Then you can do something like:

<script  type='text/javascript'>

$(document).ready(function () {
   $("a.mylink").attr("href", link);
});

</script>

If you want the text to change as well you will have to add

$("a.mylink").text(link);

to $(document).ready as well.

See it working: http://jsfiddle.net/symXp/

Upvotes: -1

Rui Lima
Rui Lima

Reputation: 7403

Sorry for any typo. Writing on my phone. Can't you create the anchor on the fly?

anchor =Document.createElement (...)
anchor.href=yourvar-value
anchor.innerText=your-value?

If a more complex thing is needed search for javascript databiding on Google

Take care

Upvotes: 0

Nitish Dhar
Nitish Dhar

Reputation: 2312

You can do it like this -

WORKING DEMO - http://codepen.io/nitishdhar/pen/rJLEH

HTML Part

<a href="" class="link">Link will be filled by javascript</a>

You need to place a specific class in the a tag. We will need this to get hold of this element from jQuery.

Javascript Part (Using jQuery)

var link = "http://google.com";
$(document).ready(function(){
  $('.link').attr('href', link);
});

We need to create a variable, link, which will hold the URL you want to assign to the a tag. Then on document ready, we get hold of the a element & update its href attribute with the link.

Upvotes: -1

Related Questions