Can I Assign URL address in Variable and use in HTML. using JavaScript?
Example:
<script>
var var_url = "/";
</script>
<a href="var_url"> Click on this link to open www.stackoverflow </a>
Above is an example to understand my question, I want to use the same URL address many times on HTML page.
Can I Assign URL address in Variable and use in HTML. using JavaScript?
Example:
<script>
var var_url = "https://stackoverflow./";
</script>
<a href="var_url"> Click on this link to open www.stackoverflow. </a>
Above is an example to understand my question, I want to use the same URL address many times on HTML page.
Share Improve this question edited Feb 5, 2019 at 7:53 Ali 2,7683 gold badges37 silver badges61 bronze badges asked Feb 5, 2019 at 7:17 SonuSonu 551 silver badge4 bronze badges 1- Hi, you should always put some effort into writing a good question for better understanding :) read more here stackoverflow./help/how-to-ask – Ali Commented Feb 5, 2019 at 7:25
4 Answers
Reset to default 2https://codepen.io/anon/pen/OdjZEY
<script>
var var_url = 'https://stackoverflow./';
</script>
<p>Open in a new window</p>
<a href="javascript:window.open(var_url);">Click on this link to open www.stackoverflow.</a>
<p>Open in the same window</p>
<a href="javascript:window.location.href
=var_url;">Click on this link to open www.stackoverflow.</a>
You could select all anchor tags with the href
of var_url
using:
[...document.querySelectorAll('[href=var_url')]
And then change each href
in this array to be the one stored in var_url
.
var var_url = "https://stackoverflow./";
[...document.querySelectorAll('[href=var_url]')].forEach(anchor => {
anchor.href = var_url;
});
<a href="var_url">Click on this link to open www.stackoverflow.</a>
<br />
<a href="var_url">You can also click here to open stackoverflow</a>
Alternatively, I think it would be better to use a class on your anchor tags, and set your URLs using:
[...document.getElementsByClassName('var_url')]
var var_url = "https://stackoverflow./";
[...document.getElementsByClassName('var_url')].forEach(anchor => {
anchor.href = var_url;
});
<a class="var_url" href="#">Click on this link to open www.stackoverflow.</a>
<br />
<a class="var_url" href="#">You can also click here to open stackoverflow</a>
You can use JavaScript to inject URL in the anchor tag.
<a id='anchor_1' href=''>Click on this link to open www.stackoverflow.</a>
<script>
var var_url = "https://stackoverflow./";
document.getElementById('anchor_1').setAttribute ('href', var_url);
</script>
In your HTML put id for access that like,
<a id="demoLink" href=""> Click on this link to open www.stackoverflow. </a>
you can do this with JavaScript like
<script>
var var_url = "https://stackoverflow./";
//change the attribute for anchor tag link
document.getElementById("demoLink").setAttribute("href", var_url);
</script>