change href attribute of link in jquery

How to Change Href Attribute of Link Using jQuery

jQuery is a powerful JavaScript library for DOM manipulations. It provides tons of features and functions to change properties of DOM elements. Sometimes you may need to change Href attribute of link on your web page. In this article, we will learn how to do this.


How to Change Href Attribute of Link Using jQuery

jQuery offers two functions .attr() and .prop() to change href and pretty much any other property of DOM elements on a web page.

Here is the syntax for each of them.

$(selector).attr(attribute_name,attribute_value);
$(selector).prop(property_name,property_value);

The key difference between attr() and prop() functions is that attr() function works with only string values of attributes while prop() function works with other data types such as boolean values. attr() function changes attribute for HTML tag. prop() function changes property as per DOM tree. So it is advisable to use prop() function instead of using attr() function.

Let us say you have the following link on your page.

<a id='mylink' class="link_class" href='http://www.example.com'>example</a>

Let us say you want to change the href to www.mysite.com.

<a id='mylink' href='http://www.mysite.com'>my site</a>

You can easily do this with the following command.

$('a').prop('href','http://www.mysite.com');

The above command will replace href attribute of all links on your page. If you want to replace href attribute of only links with class name=’link_class’ you can do so with the following command.

$('.link_class').prop('href','http://www.mysite.com');

If you have multiple links on your page, then you can select the link using its ID attribute as shown below.

$('#mylink').prop('href','http://www.mysite.com');

Or you can select the link using its href property as shown.

$("[href='http://www.example.com']").prop('href','http://www.mysite.com');

In this article, we have learnt how to change href attribute of link using jQuery.

Also read:

How to Convert String to Date in MySQL
How to Calculate Age from DOB in JavaScript
How to Escape HTML Strings in jQuery
How to Check if Element is Visible in jQuery
Set NGINX to Catch All Unhandled Virtual Hosts

Leave a Reply

Your email address will not be published. Required fields are marked *