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 get the ID of the clicked button using JavaScript/jQuery ?
Next article icon

How to change the href value of a tag after click on button using JavaScript ?

Last Updated : 07 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a high-level, interpreted, dynamically typed, and client-side scripting language. HTML is used to create static web pages. JavaScript enables interactive web pages when used along with HTML and CSS. Document Object Manipulation (DOM) is a programming interface for HTML and XML documents. DOM acts as an interface between JavaScript and HTML combined with CSS. The DOM represents the document as nodes and objects i.e. the browser turns every HTML tag into a JavaScript object that we can manipulate. DOM is an object-oriented representation of the web page, that can be modified with a scripting language such as JavaScript. To manipulate objects inside the document we need to select them and then manipulate them. Selecting an element can be done in five ways:

  • document.querySelector() Method: It returns the first element that matches the query.
  • document.querySelectorAll() Method: It returns all the elements that match the query.
  • document.getElementById() Method: It returns the one element that matches the id.
  • document.getElementsByClassName() Method: It returns all the elements that match the class.
  • document.getElementsByTagName() Method: It returns a list of the elements that match the tag name.

DOM allows attribute manipulation. Attributes control the HTML tag’s behavior or provide additional information about the tag. JavaScript provides several methods for manipulating an HTML element attribute. The following methods are used to manipulate the attributes:

  • getAttribute() method: It returns the current value of an attribute on the element and returns null if the specified attribute does not exist on the element.
  • setAttribute() method: It updates the value of an already existing attribute on the specified element else a new attribute is added with the specified name and value.
  • removeAttribute() method: It is used to remove an attribute of the specified element.

Example 1: The below code demonstrates the attribute manipulation where the href attribute of <a> tag changes on button click. A function is called on button click which updates the attribute value. The function myFunction() is a JavaScript function and it makes the HTML code more interactive by making runtime modifications.

html




<!DOCTYPE html>
<html>
<head>
    <title>
        How to change the href attribute
        dynamically using JavaScript?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <h3>
        Change the href attribute value<br>
        dynamically using JavaScript
    </h3>
      
    <a href="https://www.google.com">
        Go to Google
    </a>
      
    <br><br>
      
    <button onclick="myFunction()">
        Click Here!
    </button>
      
    <script type="text/javascript">
        function myFunction() {
            var link = document.querySelector("a");
            link.getAttribute("href");
            link.setAttribute("href",
                "https://www.geeksforgeeks.org");
            link.textContent = "Go to GeeksforGeeks";
        }
    </script>
</body>
</html>
 
 

Output:

How to change the href value of <a> tag after click on button using JavaScript ?”><figcaption>How to change the href value of <a> tag after click on button using JavaScript ?</figcaption></figure> <p><strong>Explanation:</strong> The link opens https://www.google.com before the button is clicked. when the button is clicked then the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org, Since there is only one <a> tag in the HTML document and we aim to change its attribute value, we use querySelector() and the attribute is updated using setAttribute() method.</p> <p><strong>Example 2:</strong> The link opens https://www.google.com before the button is clicked. When the button is clicked the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org. In this approach, the getElementById() method is used to select the element whose destination URL is to be changed.</p> <div class=

html




<!DOCTYPE html>
<html>
<head>
    <title>
        How to change the href attribute
        dynamically using JavaScript?
    </title>
</head>
  
<body style="text-align:center;">
      
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
      
    <h3>
        Change the href attribute value<br>
        dynamically using JavaScript
    </h3>
      
    <a href="https://www.google.com" id="myLink">
        Go to Google
    </a>
      
    <br><br>
      
    <button onclick="myFunction()">
        Click Here!
    </button>
      
    <script type="text/javascript">
        function myFunction() {
            document.getElementById('myLink').href
                ="https://www.geeksforgeeks.org";
                  
            document.getElementById("myLink")
                .textContent = "Go to GeeksforGeeks";
        }
    </script>
</body>
</html>
 
 

Output:

How to change the href value of <a> tag after click on button using JavaScript ?”><figcaption>How to change the href value of <a> tag after click on button using JavaScript ?</figcaption></figure> <div hideAd=


Next Article
How to get the ID of the clicked button using JavaScript/jQuery ?

S

Shreyasi_Chakraborty
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Change the Button Label when Clicked using JavaScript ?
    Changing the Label of the Button element when clicked in JavaScript can be used to provide more information to the user such as the text of the Submit button will change to the Submitted as soon as the form submission is completed. The below approaches can be used to accomplish this task: Table of C
    2 min read
  • How to change a button text on click using localStorage in Javascript ?
    In this article, we will learn how to change a button text using Javascript localStorage when we click on the button achieved by adding HTML onclick event listener. Approach: HTML DOM Window localStorage allows us to store key-value pairs in our browser using an object. The name of the key should be
    3 min read
  • How to change the text and image by just clicking a button in JavaScript ?
    The image and text can be changed by using JavaScript functions and then calling the functions by clicking a button. We will do that into 3 sections., in the first section we will create the structure by using only HTML in the second section we will design minimally to make it attractive by using si
    2 min read
  • How to Change Button Label in Alert Box using JavaScript ?
    In JavaScript, the alert method is used to display an alert box with a message. By default, the alert box contains an "OK" button. We cannot directly update the default alert box, However, we can customize the button label by creating a custom alert box using HTML, CSS, and JavaScript. ApproachCreat
    2 min read
  • How to get the ID of the clicked button using JavaScript/jQuery ?
    To get the ID of a clicked button using JavaScript/jQuery means identifying which specific button was clicked within a webpage. This is useful when multiple buttons exist, and you need to distinguish between them based on their unique ID for further processing. So, to get the ID of the clicked butto
    3 min read
  • How to Change the ID of Element using JavaScript?
    We are given an element and the task is to change the ID of elements using JavaScript. ID is unique for any element and it can be assigned to an element only once. JavaScript provides a method to access this id and also to manipulate the id. Syntax:Selected_element.id = newID;Below are the appraoche
    3 min read
  • How to change the text of a label using JavaScript ?
    Changing the text of a label using JavaScript involves selecting the label element and updating its textContent or innerHTML property. This allows you to modify the displayed text dynamically, often in response to user interactions or changes in data, enhancing interactivity and responsiveness. Belo
    2 min read
  • How to count the number of times a button is clicked using JavaScript ?
    At times, it becomes necessary to monitor the number of times a user clicks a button. In this article, we are going to learn how to count the number of times a button is clicked using JavaScript Below are the approaches to count the number of times a button is clicked using JavaScript Table of Conte
    3 min read
  • How to Get Value by Class Name using JavaScript ?
    This article will show you how to use JavaScript to get value by class name. To get the value of an element by its class name in JavaScript, you can use the getElementsByClassName() method. This method returns an array-like object of all elements with the specified class name. You can then access th
    2 min read
  • How to Change Text Inside all HTML Tags using JavaScript ?
    In this article, we will learn how to change the text content inside all HTML tags using JavaScript. This skill is valuable when you need to dynamically modify the text displayed on a web page. which can be useful for various scenarios like updating content, internationalization, or creating dynamic
    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