Can I Assign URL address in Variable and use in HTML. using JavaScript?
Example:
<script>
var var_url = "https://stackoverflow.com/";
</script>
<a href="var_url"> Click on this link to open www.stackoverflow.com </a>
Above is an example to understand my question, I want to use the same URL address many times on HTML page.
https://codepen.io/anon/pen/OdjZEY
<script>
var var_url = 'https://stackoverflow.com/';
</script>
<p>Open in a new window</p>
<a href="javascript:window.open(var_url);">Click on this link to open www.stackoverflow.com</a>
<p>Open in the same window</p>
<a href="javascript:window.location.href
=var_url;">Click on this link to open www.stackoverflow.com</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.com/";
[...document.querySelectorAll('[href=var_url]')].forEach(anchor => {
anchor.href = var_url;
});
<a href="var_url">Click on this link to open www.stackoverflow.com</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.com/";
[...document.getElementsByClassName('var_url')].forEach(anchor => {
anchor.href = var_url;
});
<a class="var_url" href="#">Click on this link to open www.stackoverflow.com</a>
<br />
<a class="var_url" href="#">You can also click here to open stackoverflow</a>
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