Change Link URL with JavaScript

Manipulating elements in the DOM with JavaScript is a really fun aspect of web development. When you’re first starting out in development, small JavaScript miracles are celebrated thoroughly and often. I previously published an article, Changing a URL with jQuery, which was based on a funny “Eureka!” moment a colleague had when he first began working with jQuery. I thought I’d write a new entry, complete with a new code example to showcase how to change a link URL with JavaScript. That’s right, I thought I’d use some vanilla JS this time around.

It’s very easy to change a link with JavaScript. I’ve heard of coders ditching the use of vanilla JavaScript just because it can be a bit ugly. There’s no need to worry about that issue here. When you change a link, you just need one simple line of code. This type of code would most likely be needed when listening for a certain DOM event.

Code for Changing URLs in Link with JavaScript

When you change a link URL with JavaScript, you’ll have to use the setAttribute method. Before even touching jQuery, developers should learn about basic yet useful methods like this. The code below changes an href attribute of a link to my website address.

element.setAttribute('href','http://www.ronvangorp.com');

Codepen ExampleWasn’t that easy? I made a Codepen example to help you take a deeper look at JavaScript’s setAttribute method. In this generic combination of lorem ipsum and HTML markup, I put two different links in the content that lead to different sites. We will need to decide which link URL we want to change and we can implement that change with plain JS.

The first link in the content container is for my WordPress theme SEO article. Using the getElementsByTagName method, we access the URL like we would with an array item since it’s the first of many links on the page. The first array item always has an index of 0.  Let’s go ahead and change that link to google.com. Below is the code for that action.

document.getElementsByTagName("a")[0].setAttribute("href", "http://www.google.com");

Let’s say, just maybe we don’t want to change the first link. We want to change only the second link in the content, which is the link pointing to my article about the best free photo sites. The code below will change that link to Yahoo. Since it’s the second link in the document’s ‘a’ tag array, it has an index of 1.

document.getElementsByTagName("a")[1].setAttribute("href", "http://www.yahoo.com");

Again, here is the Codepen example. Take a look at the script in action and you’ll learn how easy it is to change a link with JS. Copy it and paste it all you wish – just learn from it!

2 thoughts on “Change Link URL with JavaScript”

Comments are closed.