How to Change the Href for a Hyperlink using jQuery

To set of modify the value of the href attribute of a link or the <a> tag, you can use the jQuery .attr() method. This method can also be used to get the value of any attribute.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <a href="www.example.com">Link</a>
    <script>
      $("a").attr("href", "https://www.w3docs.com");
    </script>
  </body>
</html>

The attr() method will change the href of all hyperlinks to point to Google. For instance, you have a mix of link source and link target anchor tags:

<a name = "MyLinks"> </a> 
<a href = "http://www.w3docs.com/"> The W3Docs </a>

And you don't want to add href attributes to them. Then, you can specify the selector to match the <a> tags with an existing href attribute:

$("a[href]") //…

In case you want to match an anchor with a specific existing href, then you can do the following:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <a href="www.example.com">Link</a>
    <script>
      $("a[href]").attr("href", "https://www.w3docs.com");
    </script>
  </body>
</html>

Then you should update only some part of the href attribute:

$("a[href^='http://w3docs.com']")
  .each(function () {
    this.href = this.href.replace(/^http:\/\/beta\.w3docs\.com/,
      "http://w3docs.com");
  });

The first part only selects links where the href starts with http://stackoverflow.com. Then, a function is specified, which uses a regular expression to replace this part of the URL with a new one.

The attr() Method

The .attr() method is used to get the attribute value for the first element in the matched set. To get the value for each element, the looping construct methods, namely — .each() or .map() methods of jQuery are used.

One of the main benefits this method suggests is that it can be called directly on a jQuery object and chained to other methods.