简体   繁体   中英

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.

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> 

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 can use JavaScript to inject URL in the anchor tag.

<a id='anchor_1' href=''>Click on this link to open www.stackoverflow.com</a>

<script>
var var_url = "https://stackoverflow.com/";
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.com </a>

you can do this with JavaScript like

<script>
   var var_url = "https://stackoverflow.com/";

    //change the attribute for anchor tag link
    document.getElementById("demoLink").setAttribute("href", var_url);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM