Replace all links on the page using JavaScript and jQuery
In this guide, we will look at how to replace all links on a webpage using JavaScript and the jQuery library. This can be useful, for example, when you need to temporarily change links on a site (for a week or another period) without having to manually rewrite them.
Replacing links with exceptions
In the first example, we change all external links, excluding those that contain a certain domain. This can be useful if you want to keep the internal navigation on the site unchanged.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Iterate over all <a> tags on the page
$('a').each(function (index) {
// Check if href does not contain the specified domain
if (this.href.indexOf("http://vse-ssilki-.krome") != 0) {
// Replace href with the new URL
this.href = "http://menjaem-na-etot.domen/";
}
});
});
</script>
Learn more about the .each() method
Replacing all links without exceptions
In the second example, we simply replace all links on the page with a new URL. This can be useful for globally reconfiguring all links to a temporary or new resource.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Iterate over each <a> tag on the page
$('a').each(function (index) {
// Replace href with the new URL
this.href = "http://menjaem-na-etot.domen/chelovekopriyatniy-url/";
});
});
</script>
Learn more about the .attr() method
Implementation in pure JavaScript
For those who prefer not to use jQuery, here is how you can achieve the same result using pure JavaScript:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
// Get all <a> elements on the page
var links = document.querySelectorAll('a');
// Iterate over the obtained elements
links.forEach(function(link) {
// Change the address to the new URL
link.href = "http://menjaem-na-etot.domen/chelovekopriyatniy-url/";
});
});
</script>
Learn more about the .querySelectorAll() method