Change Link URL with jQuery

Changing a link’s URL using jQuery is a simple task. Most developers would need to put this into use while responding to user interaction or other activities. All you have to do is use the .attr method to set the URL of the link. I made an example in Codepen so you can follow along.

Code for Changing URLs in Link using jQuery

change-link-urls-with-jquery

The actual jQuery code for this example is very short and to the point. A jQuery beginner will find it easy to follow along with this example. You would simply just correctly target the right selector and assign a new URL with the .attr method. Here’s the basic syntax for it.

Presuming a paragraph with the class “first” has a link in it, we’d first have to target the link inside the correct paragraph tag. We can switch the URL by inputting the following jQ code:

$(document).ready(function() {
 $('p.first a').attr('href','http://ronvangorp.com/web/cgit/cgt_courses.html');
 });

This jQuery code will change the link’s address to http://ronvangorp.com/web/cgit/cgt_courses.html, one of the pages I created while going to college at Purdue Calumet. Using the right selector will allow you to target almost any link that you may have in your page’s content.

There are many ways to hook into a link and change the address in it. We can target the links inside the first paragraph on a page with the following code:

$('p:nth-of-type(1) a').attr('href','http://www.bloody-disgusting.com');

You’ll find out that this will reassign the href attribute of the link to bloody-disgusting.com, my favorite horror movie site. Lastly, you can target a link that only has a certain URL. Let’s say a link has yahoo.com in it and you want to replace it with google.com. You can use the following lines of code to achieve this:

$("a[href='http://www.yahoo.com']").attr('href', 'http://www.google.com/');

You can view the example here in my Codepen.

7 thoughts on “Change Link URL with jQuery”

  1. Very nice post. I just stumbled upon your blog and wished to say I found your solution very useful!

  2. Great post. I was checking constantly this blog and I’m impressed! Extremely useful information 🙂 Thank you and best of luck.

Comments are closed.