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


The jQuery attr() method is used to change the href attribute for a hyperlink. Query attr() method is used to fetch the value of any standard attribute from the matched HTML element(s). Let us see an example.

First, get the current URL −

var httpUrl = $(this).attr("href"); 

Create a new URL by replacing the above using the replace() −

var httpsUrl = httpUrl.replace("http://", "https://");

We will convert the https links to link using what we saw above −

<p><a href="http://www.tutorialspoint.com">Tutorialspoint</a></p> <p><a href="http://www.tutorialspoint.com/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="http://www.tutorialspoint.com/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="http://www.tutorialspoint.com/questions/index.php">Tutorialspoint QA</a></p>

Example

Let us see the complete example to change the href attribute for a hyperlink −

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script> <script> $(document).ready(function(){ $('a[href^="http://"]').each(function(){ var httpUrl = $(this).attr("href"); // Get current url var httpsUrl = httpUrl.replace("http://", "https://"); // Create new url $(this).attr("href", httpsUrl); }); }); </script> </head> <body> <h1>Old to New URL</h1> <p>We have converted http to https below:</p> <p><a href="http://www.tutorialspoint.com">Tutorialspoint</a></p> <p><a href="http://www.tutorialspoint.com/market/index.asp">Tutorialspoint Courses</a></p> <p><a href="http://www.tutorialspoint.com/latest/ebooks">Tutorialspoint EBooks</a></p> <p><a href="http://www.tutorialspoint.com/questions/index.php">Tutorialspoint QA</a></p> </body> </html>

Output

Updated on: 01-Nov-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements