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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to create multi-line strings in JavaScript ?
Next article icon

How to Create a Link in JavaScript ?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement(‘a’), setting attributes like href and textContent, and then appending it to the document with appendChild().

Here are some common approaches to Create a Link in JavaScript:

Table of Content

  • Using createElement and appendChild() Method
  • Using createElement and prepend() Method
  • Using innerHTML

Using createElement and appendChild() Method

The createElement and appendChild approach involves creating an HTML element (like <a>) using a document.createElement(), setting its attributes (e.g., href), appending text or other nodes using appendChild(), and then inserting it into the DOM with `appendChild().

Example 1: In this example, we create a button that, when clicked, dynamically generates a hyperlink using JavaScript. The link points to “https://www.geeksforgeeks.org” and is displayed on the webpage.

html
<!DOCTYPE HTML> <html>  <head>     <title>         Using createElement and appendChild() Method     </title> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </h1>      <p id="GFG_UP" style="font-size: 19px; font-weight: bold;">     </p>      <button onclick="GFG_Fun()">         click here     </button>      <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;">     </p>      <script>         let el_up = document.getElementById("GFG_UP");         let el_down = document.getElementById("GFG_DOWN");          el_up.innerHTML = "Click on the button to generate "             + "a link using JavaScript.";          function GFG_Fun() {              // Create anchor element.             let a = document.createElement('a');              // Create the text node for anchor element.             let link = document.createTextNode("This is link");              // Append the text node to anchor element.             a.appendChild(link);              // Set the title.             a.title = "This is Link";              // Set the href property.             a.href = "https://www.geeksforgeeks.org";              // Append the anchor element to the body.             document.body.appendChild(a);         }     </script> </body>  </html> 

Output:

 Raja Software Labs Recruitment Process

Using createElement and prepend() Method

The Using createElement with prepend for DOM Manipulation approach dynamically creates HTML elements, such as links, using createElement. It sets attributes like href and text content, then inserts the element at the start of a specified parent element using prepend.

Example : In this example we dynamically creates a link using createElement and prepend. Clicking the button generates an anchor element with specified text, title, and URL, adding it to the top of the body.

html
<!DOCTYPE HTML> <html>  <head>     <title>         Using createElement and prepend     </title> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </h1>      <p id="GFG_UP" style="font-size: 19px;                            font-weight: bold;">     </p>      <button onclick="GFG_Fun()">         click here     </button>      <p id="GFG_DOWN" style="color: green;                              font-size: 24px;                              font-weight: bold;">     </p>      <script>         let el_up = document.getElementById("GFG_UP");         let el_down = document.getElementById("GFG_DOWN");          el_up.innerHTML = "Click on the button to generate "             + "a link using JavaScript.";          function GFG_Fun() {              // Create anchor element.             let a = document.createElement('a');              // Create the text node for anchor element.             let link = document.createTextNode("This is link");              // Append the text node to anchor element.             a.appendChild(link);              // Set the title.             a.title = "This is Link";              // Set the href property.             a.href = "https://www.geeksforgeeks.org";              // Append the anchor element to the body.             document.body.prepend(a);         }     </script> </body>  </html> 

Output:

 Raja Software Labs Recruitment Process

Using innerHTML

The innerHTML approach involves setting the HTML content of an element directly by assigning a string that includes the desired HTML tags, like an anchor <a>. This method is quick for inserting HTML but can overwrite existing content and disrupt event listeners.

Example: In this example innerHTML is used to insert HTML content directly into the element with id=”GFG_DOWN”, allowing the creation of a link dynamically when the button is clicked.

HTML
<!DOCTYPE HTML> <html>  <head>     <title>        Using innerHTML     </title> </head>  <body style="text-align:center;">      <h1 style="color:green;">         GeeksForGeeks     </h1>      <p id="GFG_UP" style="font-size: 19px;                            font-weight: bold;">     </p>      <button onclick="GFG_Fun()">         click here     </button>      <p id="GFG_DOWN" style="color: green;                              font-size: 24px;                              font-weight: bold;">     </p>      <script>         let el_up = document.getElementById("GFG_UP");                  let el_down = document.getElementById("GFG_DOWN");          el_up.innerHTML = "Click on the button to generate "             + "a link using JavaScript.";          function GFG_Fun() {             // Use innerHTML to create and insert the link             el_down.innerHTML =  '<a href="https://www.geeksforgeeks.org" title="This is Link">This is link</a>';         }     </script> </body>  </html> 

Output:

Alinkbyjs


JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Next Article
How to create multi-line strings in JavaScript ?

P

PranchalKatiyar
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javaScript
  • JavaScript-Questions
  • Web technologies

Similar Reads

  • How to Create a New Line in JavaScript ?
    A new line can be made in JavaScript using the below-discussed methods. Using Escape Sequence `\n`The \n escape sequence represents a newline character in JavaScript strings and it can used to render a new line in JavaScript. [GFGTABS] JavaScript console.log("GfG"); console.log("\n
    3 min read
  • How to Create an Alert in JavaScript ?
    The alert() method in JavaScript displays an alert box with a message and an OK button. It's used when you want information to come through to the user, providing immediate notifications or prompts for user interaction during program execution. Note: Alert boxes interrupt user interaction, shifting
    1 min read
  • How to create multi-line strings in JavaScript ?
    In JavaScript, the absence of native support for multi-line strings was a longstanding challenge. However, with the advent of ES6 (ECMAScript 2015), the things changed dramatically. ES6 introduced string literals, offering robust support for multi-line strings, which was a significant enhancement fo
    3 min read
  • How to create HTML List from JavaScript Array?
    Creating an HTML list from a JavaScript array allows you to dynamically generate <ul> (unordered) or <ol> (ordered) lists and fill them with data directly from your array. This is useful when you want to display array data in a structured way on your webpage. In this guide, we’ll go thro
    3 min read
  • How to Create a String with Variables in JavaScript?
    To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String methods. Here are the common approaches: 1. Template Literals (Recommended)Template literals are the modern and most preferred way to create strings with va
    2 min read
  • How to create an element from a string in JavaScript ?
    In this article, we will learn how to create an element from a string using JavaScript. This can be used in situations where dynamically generated elements are required by the user. This can be achieved using many approaches as given below: Table of Content Using the createElement() methodUsing the
    3 min read
  • How to Simulate a Click in JavaScript?
    Simulating a click in JavaScript means triggering a click event on an HTML element using code, rather than requiring manual user interaction. This technique is useful for automating actions like clicking buttons, links, or other interactive elements, enhancing web functionality, and triggering hidde
    3 min read
  • How to Create Keyboard Shortcuts in JavaScript ?
    This article will demonstrate how to create keyboard shortcuts in JavaScript. We can manually set user-defined functions for different shortcut keys. Keyboard shortcuts allow users to perform actions quickly by pressing a combination of keys, such as Ctrl + S for saving, Ctrl + C for copying, or cus
    4 min read
  • How to Create Query Parameters in JavaScript ?
    Creating query parameters in JavaScript involves appending key-value pairs to a URL after the `?` character. This process is essential for passing data to web servers via URLs, enabling dynamic and interactive web applications through GET requests and URL manipulation. Example: Input: {'website':'ge
    3 min read
  • How to access history in JavaScript ?
    In this article, we will learn how to access history in JavaScript. We will use the History object to access the history stack in JavaScript. Every web browser will store the data on which websites or webpages opened during the session in a history stack. To access this history stack we need to use
    3 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