How to change href attribute of a hyperlink using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery .attr() Method

You can use the jQuery .attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

The following example will show you how to convert all hyperlinks or links in a document from "http" to "https" at runtime with jQuery.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Set HREF for Anchor Tag</title>
  • <script src=""></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $('a[href^="http://"]').each(function(){ 
  •             var oldUrl = $(this).attr("href"); // Get current url
  •             var newUrl = oldUrl.replace("http://", "https://"); // Create new url
  •             $(this).attr("href", newUrl); // Set herf value
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <p><a href="">Google</a></p>
  •     <p><a href="">Gmail</a></p>
  • </body> 
  • </html> 

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.