Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
Cypress - Get Attribute value and store in Variable
Next article icon

How to insert a JavaScript variable inside href attribute?

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

Table of Content

  • Using onclick property
  • Using document.write
  • Using Template Literals

Example: 

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

Using onclick property

  • This method uses the ‘onclick‘ property of the ‘a’ tag, i.e., whenever the link (‘a’ tag) is clicked, an ‘onclick‘ event is triggered. Here we will use this onclick event to generate a new URL and redirect the user to that URL. (NOTE: This URL will contain the Variable we want to use inside the href attribute) 
  • Now we will set the URL.
  • “location.href” -> It is the entire URL of the current page.
  • “this” -> Refers to the ‘a’ tag that has been clicked.
  • “this.href” -> fetches the href value from the ‘a’ tag.
  • Once we have “this.href”, append the variable to it (Here we have used a variable named “XYZ”).
  • Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it.

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

HTML
<!DOCTYPE html> <html>  <head>     <title>GeeksforGeeks</title>     <script>         let val = 55;     </script> </head>  <body>      Link to <a href= "https://www.google.com/"      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

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”. 

html
<!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.

Using Template Literals

Template literals are string literals allowing embedded expressions. We can use template literals to dynamically construct the href attribute by directly embedding the JavaScript variable within the URL string.

Example:

JavaScript
<!DOCTYPE html> <html>  <head>     <title>Dynamic Href</title> </head>  <body>     <!-- Using standard HTML for the href initially -->     Link to <a id="dynamicLink" href="#">Google</a>      <script>         // Define the variable         let val = 55;          // Function to update the href         function updateHref() {             const link = document.getElementById("dynamicLink");             link.href = `https://www.google.com/?xyz=${val}`;         }          // Update the href when the document is loaded         document.addEventListener("DOMContentLoaded", updateHref);     </script> </body>  </html> 

Output:

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

In this approach, we directly embed the JavaScript variable val within the URL string using template literals, making the code cleaner and easier to read.



Next Article
Cypress - Get Attribute value and store in Variable
author
7maestro
Improve
Article Tags :
  • AngularJS
  • JavaScript
  • Web Technologies
  • HTML-Attributes
  • JavaScript-Questions

Similar Reads

  • Cypress - Get Attribute value and store in Variable
    In Cypress, you can retrieve an attribute value of an element using the .invoke() method. This is helpful when you need to store an attribute value for further use in your test. For instance, you might want to grab the value of a href, id, or src attribute from an element and then perform assertions
    3 min read
  • How to get an attribute value from a href link in Selenium java?
    When working with Selenium WebDriver in Java, automating web interactions often involves handling hyperlinks. A common task is to extract the attribute value from a <a> tag, specifically the href attribute, which contains the link's destination URL. Extracting this href value allows you to ver
    3 min read
  • How to Display JavaScript Variable Value in Alert Box ?
    JavaScript is a powerful scripting language widely used in web development to enhance user interactivity and functionality. Often, developers need to display variable values to users, either for debugging purposes or to provide informative messages. One common method to achieve this is by using an a
    3 min read
  • How to Display JavaScript Variable Value in Alert Box ?
    An alert box is a dialog box that pops up on the screen to provide information to the user. It contains a message and an OK button, which allow users to acknowledge the message and close the box. Alert boxes are commonly used in web development to display important messages, warnings, or notificatio
    2 min read
  • How to hide span element if anchor href attribute is empty using JavaScript ?
    The task is to hide the <span> tag when href attribute of <a> tag is not present or invalid. Let us consider we have <a> tag inside the <span> tag. It will look similar to this: <span><a href="www.google.com"></a></span> Now we add the id to the elemen
    2 min read
  • How to Use Dynamic Variable Names in JavaScript?
    Dynamic variable names are variable names that are not predefined but are generated dynamically during the execution of a program. This means the name of a variable can be determined at runtime, rather than being explicitly written in the code. Here are different ways to use dynamic variables in Jav
    2 min read
  • How to Target a Frame with a Hyperlink in JavaScript?
    Targeting a specific frame from a hyperlink using JavaScript allows for better content control in web applications. NOTE: Frames have been deprecated and should not be used by modern websites like HTML 5 type. However, the ability to place one document inside another still exists through iframes, ta
    3 min read
  • How to Pass variables to JavaScript in Express JS ?
    Express is a lightweight framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. When working with Express.js you may encounter scenarios where you
    2 min read
  • How to Add JavaScript in HTML Document?
    To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other e
    4 min read
  • How to change href attribute of a hyperlink using jQuery ?
    Changing the href attribute of a hyperlink using jQuery refers to the process of modifying the URL a link directs to without altering the HTML manually. This capability is useful for creating dynamic web applications where link destinations need to change based on user interactions or other conditio
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences