How to change the href attribute for a hyperlink using jQuery?

In this tutorial, let's see that how can we change the href attribute for a hyperlink using jQuery?
Submitted by Pratishtha Saxena, on June 17, 2022

jQuery is a JavaScript library. It makes things like HTML document traversal and manipulation, and event handling, much simpler with an easy-to-use API.

For changing the href attribute for the hyperlink we'll use the Attribute Method of jQuery. This method, attr(), is used to get and set the values of the specified attribute.

Syntax:

$(selector).attr(attribute,value)

Here, the selector is the HTML element. Attribute, will be href and value will be the specified value that you want to set.

Now, for example:

$("a").attr("href", "http://www.google.com/")

This is a jQuery code that will change the attribute href of the anchor tag here. But this will be applied to every anchor tag in the HTML document. Even if there are some anchor tags that don't have the href as its attribute, then this jQuery code will set the href attribute to those anchor tags, which is not what we want.

So, to be specific on what element has to be targeted, the id of the element will be specified.

Note: Always remember to apply the CDN link while working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Example:

HTML Code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <center>
         <h1><a id="link" href="https://www.wikipedia.com">Visit The Website...!!!</a></h1>
      </center>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
        $("#link").attr('href','https://www.google.com');
    });
</script>

Output:

Example: Change the href attribute





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.