How to change the href attribute for a hyperlink using jQuery
javascriptYou can change the href attribute of a hyperlink using jQuery’s attr() method. Here’s an example:
HTML:
<a id="myLink" href="https://example.com">Click me!</a>
JavaScript (with jQuery):
$(document).ready(function() {
// Change the href attribute of the link
$('#myLink').attr('href', 'https://newurl.com');
});
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 ”https://newurl.com”. 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', 'https://newurl.com');
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.
![](/image/facebook_icon.png)
![](/image/twitter_icon.png)
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame