W3docs

How to Change the Href for a Hyperlink using jQuery

Read this JavaScript tutorial and learn the easy way of changing the href attribute for a hyperlink step by step by using one of the methods of jQuery.

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

javascript jquery attr method

<!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 <kbd class="highlighted">attr()</kbd> method will change the href of all hyperlinks to point to a new URL. For instance, you have a mix of link source and link target anchor tags:

javascript jquery attr method

<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 <kbd class="highlighted"> XFI5 </kbd> tags with an existing href attribute:

javascript jquery a href

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

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

javascript jquery attr method

<!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:

javascript jquery attr method

$("a[href^='http://beta.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://beta.w3docs.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 <kbd class="highlighted">.attr() </kbd> 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 — <kbd class="highlighted">.each() </kbd> or <kbd class="highlighted">.map() </kbd> methods of jQuery are used.

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