1

I have the below code:

<a href="#">launch</a>

and I have the value which is to be substituted in the place of '#' received from a function call in Javascript. Let's say the value is 'www.google.com' and is stored in the variable abc in the function url();.

Is there any way I can replace the '#' dynamically with the variable value from the function?

Please do help me out. Many thanks!

Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
Rahul Sudha
  • 137
  • 2
  • 7
  • Its going to be a lot easier if you have an `id` or a `class` on your anchor tag. Cn you show what JavaScript code you currently have? – putvande Dec 27 '16 at 18:37
  • Hello @putvande, here's the js snippet; – Rahul Sudha Dec 27 '16 at 18:38
  • Hello @putvande, here's the js snippet; `var abc = 'mailto:'+dom2+'?subject='+tempsubj2+'&cc='+ccvl;` i want thus value of abc to come instead on '#' – Rahul Sudha Dec 27 '16 at 18:42
  • I have myself found a simple way to solve this problem. what i did was, i altred the code from: `launch` to `launch` and in java-script, i called like this: `var abc = 'www.google.com';` `document.getElementById('test').innerHTML= 'launch';` and i got the result which i was expecting! This just changed the entire line of code instead of '#' which anyway did the job..!! – Rahul Sudha Dec 28 '16 at 07:31

5 Answers5

2

here is another way to do this, using jquery

$("a").attr("href", "http://www.google.com/")
Rehan Shikkalgar
  • 1,029
  • 8
  • 16
1

Add an id attribute in your HTML:

<a id="some-id" href="#">launch</a>

Then, in your JavaScript:

document.getElementById('some-id').href = 'new-href'

document.getElementById() gets the DOM object with the specified id. .href access the target of the anchor tag, a property of the DOM object.

Further reading.

noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
0

Without jQuery:

document.querySelector('a').href = yourVar;
0

You could use setAttribute

<a href="#" id="link">launch</a>

document.getElementById("link").setAttribute("href", "www.google.com");
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

If you want to use an id then you could do this:

 <a id="myLink" href="#">launch</a>

And using jQuery(This is using JQuery, not exactly pure JavaScript syntax):

var hrefResult = $("#myLink").attr("href")
AlexGH
  • 2,735
  • 5
  • 43
  • 76
  • 1
    *"Unless another tag for a framework/library is also included, a pure JavaScript answer is expected."* – Felix Kling Dec 27 '16 at 18:46
  • @FelixKling you are right, this is more a JQuery answer, I've edited my answer and this is just other option – AlexGH Dec 27 '16 at 18:49