Search code examples
htmlhrefvar

HTML: url = <name var>


As href argument, I would like to put a variable.

Instead of:

<p><a href="http://www.google.com">Go to Google</a></p>

</body>
</html>

I would like to write something as:

<html>
<body>

var link = "http://www.google.com"
<p><a href=link>Go to Google</a></p>

</body>
</html>

Solution

  • You can do something like this:

    <html>
    <head>
    </head>
    
    <body>
    <p><a id="some-link">Some link</a> is here</p>
    
    <script>
      var link = 'http://www.google.com';
    
      var someLink = document.querySelector('#some-link');
      someLink.setAttribute('href', link);
    </script>
    </body>
    </html>
    

    The script tag executes javascript actions. This one specifically sets the href of the given item with the some-link id. The # means "element with the id".

    You can try it over here. https://jsfiddle.net/94ct5hvr/