-1

Hi I would like to put a dynamic link in a href tag with window.location.href

How can I do this?

<a href="https://twitter.com/share?url="+ <script> window.location.href </script>+ "&text=!" target="_blank">
  Twitter
</a>
AttackTheWar
  • 219
  • 1
  • 12

2 Answers2

0

You could give the a an id and look it up by that.

document.getElementById('foo').setAttribute('href', `https://twitter.com/share?url="${window.location.href}&text=!`);
<a id="foo" target="_blank">
  Twitter
</a>
baao
  • 71,625
  • 17
  • 143
  • 203
0

You can try the following way:

var el = document.querySelector('a');
el.href = el.href+window.location.href + '&text=!';
<a href="https://twitter.com/share?url=" target="_blank">
  Twitter
</a>
Mamun
  • 66,969
  • 9
  • 47
  • 59