jQuery change href value

jQuery change href value

Changing the href value of an anchor tag using jQuery is a common task in web development. Here are a few ways to accomplish it:

Method 1: Using attr()

The attr() method in jQuery allows you to get or set the value of an attribute for a selected element. To change the href value of an anchor tag using attr(), you can do the following:

$(document).ready(function(){
  $('a').attr('href', 'https://www.google.com');
});

This code will change the href value of all anchor tags on the page to "https://www.google.com". You can replace "a" with a more specific selector if you only want to change the href value of certain anchor tags.

Method 2: Using prop()

The prop() method in jQuery allows you to get or set the value of a property for a selected element. To change the href value of an anchor tag using prop(), you can do the following:

$(document).ready(function(){
  $('a').prop('href', 'https://www.google.com');
});

This code will change the href value of all anchor tags on the page to "https://www.google.com". You can replace "a" with a more specific selector if you only want to change the href value of certain anchor tags.

Method 3: Using the attr() function with a callback

You can also use the attr() function with a callback function to change the href value of an anchor tag based on its current value. Here's an example:

$(document).ready(function(){
  $('a').attr('href', function(index, oldValue) {
    return oldValue + '?query=123';
  });
});

This code will append "?query=123" to the current href value of all anchor tags on the page.

These are some of the ways to change the href value of an anchor tag using jQuery. Choose the method that best suits your needs and implement it in your project!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe