How to change the href Attribute value for a Hyperlink with little bit jQuery ?

On 08.06.14, In jQuery

When coding with jQuery, at some point or the other you would want to modify the source of a particular hyperlink using jQuery. In this micro post we will help you with some simple code snippets on how you can change the href attribute of a given by applying just a tricky jQuery logic. The only thing that you need to be careful about with this is that you will have to be particular with you selector when you are targeting a link otherwise the possibility is that your other web pages will be overridden. For instance, let us suppose that there is a hyperlink that points to orkut.com and now your project requires you to change the hyperlink to facebook.com then you can do this by employing the simple code snippet shown below:

1
$("a [href="http://www.orkut.com/"]").attr ("href", "http://www.facebook.com/")

However if you would like to change all the hyperlinks on your webpage to point to a custom link say yahoo then the below code snippet will help you modify this:

1
$("a”).attr ("href", "http://www.yahoo.com/")

For jQuery version above 1.6, you can use prop () instead of attr () to change the href of a hyperlink, so the above code for higher versions can be replaced as:

1
$("a”).prop ("href", "http://www.yahoo.com/")

Scroll to Top