How to change the href for a hyperlink using jQuery

How can you change the href for a hyperlink using jQuery?


solution

Even though the OP explicitly asked for a jQuery answer, you don’t need to use jQuery for everything these days.

A few methods without jQuery:

-

If you want to change the href value of all <a> elements, select them all and then iterate through the nodelist: (example)

var anchors = document.querySelectorAll('a');
Array.prototype.forEach.call(anchors, function (element, index) {
  element.href = "http://stackoverflow.com";
});

-

If you want to change the href value of all <a> elements that actually have an href attribute, select them by adding the [href] attribute selector (a[href]): (example)

var anchors = document.querySelectorAll('a[href]');
Array.prototype.forEach.call(anchors, function (element, index) {
  element.href = "http://stackoverflow.com";
});

-

If you want to change the href value of <a> elements that contain a specific value, for instance google.com, use the attribute selector a[href*="google.com"]: (example)

var anchors = document.querySelectorAll('a[href*="google.com"]');
Array.prototype.forEach.call(anchors, function (element, index) {
  element.href = "http://stackoverflow.com";
});

Likewise, you can also use the other attribute selectors. For instance:

-

a[href$=".png"] could be used to select <a> elements whose href value ends with .png.

-

a[href^="https://"] could be used to select <a> elements with href values that are prefixed with https://.

-

If you want to change the href value of <a> elements that satisfy multiple conditions: (example)

var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]');
Array.prototype.forEach.call(anchors, function (element, index) {
  element.href = "http://stackoverflow.com";
});

..no need for regex, in most cases.