Open In App
Related Articles

How to change href attribute of a hyperlink using jQuery ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will see how to change the href attribute of hyperlinks using jQuery. There are two ways or methods available in jQuery that we can use to change the URL of the href attribute.

Using the attr() method

The attr() method in jQuery is used to set or return the attributes and their values associated with the selected element. We can directly pass the href attribute and the new URL value to this method as parameters to change the URL.

Syntax:

$(selector).attr('href', 'newURL');

Example: In this example, we will change the href attribute value using the attr() method and change the display text using the jQuery text() method.

HTML

<!DOCTYPE>
<html>
 
<head>
    <title>
        How to change href attribute
        of a hyperlink using jQuery?
    </title>
 
    <script src=
    </script>
 
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <h3>
        How to change href attribute of
        <br>a hyperlink using jQuery?
    </h3>
 
        target="_blank" id="GFG">
    </a>
    <br><br>
 
    <button>Change URL</button>
 
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("a").attr("href",
 
                $("#GFG").text(
            });
        });
    </script>
</body>
 
</html>

                    

Output:

Using the prop() method

The prop() method can also be used to change the URL of the href attribute by passing the href property and the new URL value as parameters in the same way we did with the attr() method in the last example.

Syntax:

$(selector).prop('href', 'newURL');

Example: The below example will explain the use of the prop() method to change the URL of the href attibute.

HTML

<!DOCTYPE>
<html>
 
<head>
    <title>
        How to change href attribute
        of a hyperlink using jQuery?
    </title>
 
    <script src=
    </script>
 
    <style>
        body {
            text-align: center;
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h1>GeeksforGeeks</h1>
 
    <h3>
        How to change href attribute of
        <br>a hyperlink using jQuery?
    </h3>
 
        target="_blank" id="GFG">
    </a>
    <br><br>
 
    <button>Change URL</button>
 
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("a").prop("href",
 
                $("#GFG").text(
            });
        });
    </script>
</body>
 
</html>

                    

Output:



Last Updated : 14 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads