Skip to content
the poor coder

jQuery change href value

Poor Man
Published
Reading time
1 min read
On this page

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:

Text
$(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:

Text
$(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:

Text
$(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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC