Problem: Need to change all the relative urls on a page and replace with an absolute url.
Different from my other post I’m going to separate the concerns of this problem: 1 being selecting only the links that are relative and not inline or mailto: links; 2 modifying the href.
Selecting the links on a page
The jQuery standard $(‘a’) will only solve half our problem because we only want links that are relative. There are several different methods we can use with jQuery to get exactly what you need, however first take into context what your page actually looks like. You may be able to save some time if your page has relatively few links, on the other hand if you have a page with hundreds of links you will need to chose your selectors wisely. To make the best and most informed decision, I suggest you test your various use cases @ http://jsperf.com/.
Here are three that I came up with:
1 2 3
I’m going to use the first one just because it is a little bit more succinct. Now that we have all of the relative links on the page we need modify the href for each one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Live example below, hover over the links to see the urls before, click the button and check them again, all of the relative links will become absolute with the new domain.
Thanks for reading my post, I hope it was helpful.