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("https://", "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^="https://"]').each(function(){ var httpUrl = $(this).attr("href"); // Get current url var httpsUrl = httpUrl.replace("https://", "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: 2022-11-01T12:48:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements