Skip to content
the poor coder

replace link in javascript

Poor Man
Published
Reading time
1 min read
On this page

Replacing a link in JavaScript can be done in several ways. In this article, we will discuss the most common methods.

Method 1: Using the getElementById() Method#

The first method involves using the getElementById() method to select the link element and then changing the value of its href attribute.

Text
var link = document.getElementById("myLink");
link.href = "https://www.newlink.com";

In the above code, we first select the link element with the ID "myLink" using the getElementById() method. We then change the value of its href attribute to the new link URL.

Method 2: Using the querySelector() Method#

The second method involves using the querySelector() method to select the link element and then changing the value of its href attribute.

Text
var link = document.querySelector("a[href='https://www.oldlink.com']");
link.href = "https://www.newlink.com";

In the above code, we use the querySelector() method to select the link element with the old link URL. We then change the value of its href attribute to the new link URL.

Method 3: Using Regular Expressions#

The third method involves using regular expressions to find and replace the old link URL with the new one.

Text
var content = document.body.innerHTML;
content = content.replace(/https:\/\/www.oldlink.com/g, "https://www.newlink.com");
document.body.innerHTML = content;

In the above code, we first get the HTML content of the page using the innerHTML property of the document.body object. We then use a regular expression to find and replace all instances of the old link URL with the new one. Finally, we set the new HTML content of the page back to the document.body object.

Conclusion#

These are the three most common ways to replace a link in JavaScript. Choose the method that best suits your needs and implement it in your code.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC