Open In App

How to insert a JavaScript variable inside href attribute?

To insert a JavaScript variable inside the href attribute of an HTML element, <a > … </a> tags are used. One of the attributes of ‘a’ tag is ‘href’.

href: Specifies the URL of the page the link goes to.



Below are the Methods to use Variables inside this ‘href’ attribute: 

Example: 

<a href="https://www.geeksforgeeks.org/">
    GeeksforGeeks
// Using href attribute for url. </a>

Approach 1: Using onclick property

Example: In the example below, we will append a variable named ‘XYZ’ and its value is 55.




<!DOCTYPE html>
<html>
 
<head>
    <title>GeeksforGeeks</title>
    <script>
        let val = 55;
    </script>
</head>
 
<body>
 
    Link to <a href=
    onclick="location.href=this.href+'?xyz='+val;return false;">
        Google
    </a>
 
</body>
 
</html>

Output: This result will be shown in the searchbar.

Resultant Url: https://www.google.com/?xyz=55

Approach 2: Using document.write

When an HTML document is loaded into a web browser, it becomes a document object. This document object has several functions, one of which is written (). write(): Writes HTML expressions or JavaScript code to a document 

Example: In this method, we will use this write() function to create an “a tag”. 




<!DOCTYPE html>
<html>
 
<head>
    <title>GeeksforGeeks</title>
    <script>
        let val = 55;
    </script>
</head>
 
<body>
    Link to
    <script>
        let loc = "https://www.google.com/?xyz=" + val;
        document.write('<a href="' + loc + '">Google</a>');
    </script>
</body>
 
</html>

Output: This result will be shown in the searchbar.

Resultant Url: https://www.google.com/?xyz=55

‘val’ is the javascript variable that stores the value that we want to pass into the URL. The URL has a variable named ‘XYZ’ that takes value = 55 from the javascript variable val.


Article Tags :