Blog Change the href Value for a Group of Links
July 31, 2013 Development, jQuery Social Share
The contact link was on various pages in the client’s many call to action areas. I could have installed a search and replace plugin to accomplish my task which would have changed the HTML directly and been a more permanent solution. However, I turned to jQuery for a quick and temporary fix in case the client decided to revert the change.
In jQuery version 1.6 and later, we can use the .prop() method to target the href attribute and update all of the links.
// Searching for cta-button class $('a.cta-button').prop('href', '/contact-us/');
In my case, the links were buttons so they all had a class of cta-button that I could easily target. If the links didn’t have a common class assigned to them, we could use the following syntax with the carrot before the equal sign to change every mailto: link on the website.
// Change all mailto: links $('a[href^="mailto"]').prop('href', '/contact-us/');
If there were multiple mailto: links on the website, we could target the exact email address we wanted to change.
// Search for email $('a[href="mailto:contact[at]website.com"]').prop('href', '/contact-us/');
Prior to jQuery version 1.6, we needed to use the .attr() method. You can see below that the only difference is the name of the method being called. For an in-depth conversation about the benefits of using .prop() over .attr(), please check out Stack Overflow.
// Prior to jQuery v1.6 $('a.cta-button').attr('href', '/contact-us/');
Although I defined the absolute URL /contact-us/ as the new href attribute, we can also use external domains such as http://www.google.com.