Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Assign URL address in Variable and use in HTML. using JavaScript?

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.

like image 886
Sonu Avatar asked Sep 12 '25 22:09

Sonu


2 Answers

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>

like image 173
Armel Avatar answered Sep 15 '25 11:09

Armel


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>
like image 31
Nick Parsons Avatar answered Sep 15 '25 12:09

Nick Parsons