jQuery

jQuery Change href (Hyperlink) Examples

At some point of time, you may be required to change the source of a hyperlink using jQuery. In this article, I am going to provide you with a simple 1 line solution to change href of a hyperlink dynamically using jQuery.

How to Change href (Hyperlink) Value using jQuery – Examples

Let’s say that you have a hyperlink that points to hotmail.com. You now want to update the hyperlink to bing.com. You can do it in the following way:

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

If you wan to change href of all links in a page to point to a custom link , use following code:

$("a").attr("href", "http://www.bing.com");

For jQuery version 1.6+, you can use the function “prop()” to make the change. So the above code can be rewritten as:

$("a").prop("href", "http://www.bing.com");

attr vs prop: Which one to use?

attr is meant for html attributes as they are strictly defined.

prop is mean to get property value.  Such a property on that DOM object should exist in order to receive the value.

For example, consider:

<div custom = "extreme" >

$('div').attr('custom'): returns 'extreme'
$('div').prop('custom'): returns undefined

As you can see, you can use “attr” to even get the value of a custom attribute that you may have defined on an element whereas using “prop” will require the property to actually be a standard property of that element.

That’s it!

Do you know of any other ways to to change href or change hyperlink using jQuery? Feel free to suggest by commenting below.

3 Comments on jQuery Change href (Hyperlink) Examples

  1. 1

    Hello,

    thanks for post, I found it at google. Maybe do you know more convinient way to add attributes, instead of:

    $(‘a’).attr(‘href’, ‘http://google.com?param1=’ + someVar + param2 + anotherVar + …) et.c.?

  2. 3

    You’re the man!!

Leave a Reply to Jame Robert Cancel reply

*

*