How can you change the href for a hyperlink using jQuery?
Even though the OP explicitly asked for a jQuery answer, you don't need to use jQuery for everything these days.
If you want to change the href value of all 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 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 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:
If you want to change the href value of 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.