How to change the href attribute for a hyperlink using jQuery


You can change the href attribute of a hyperlink using jQuery’s attr() method. Here’s an example:


<a id="myLink" href="">Click me!</a>

JavaScript (with jQuery):

$(document).ready(function() {
  // Change the href attribute of the link
  $('#myLink').attr('href', '');

In this example, we use jQuery’s $(document).ready() function to execute the code within the function once the document is fully loaded. Within the function, we use the attr() method to change the href attribute of the myLink element to a new value, which in this case is ””. You can replace this value with any URL you want to set as the new destination for the link.

Note that you can also use the prop() method to change the href attribute, like this:

$('#myLink').prop('href', '');

Both attr() and prop() methods can be used to change the attribute of an element. However, there are some differences between them. In general, you should use attr() to get or set attributes that are part of the HTML markup, and use prop() to get or set properties of DOM elements, such as the checked property of a checkbox or radio button. In the case of the href attribute of an anchor element, either method can be used interchangeably.