In this example you will learn, How to change href attribute of a hyperlink using jQuery 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Set HREF for Anchor Tag</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> $(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="http://www.google.com">Google</a></p> <p><a href="http://www.gmail.com">Gmail</a></p> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.