Dave Thompson
Dave Thompson

Reputation: 23

Changing href attribute leveraging Javascript

Currently looking to dynamical change the href attribute on the <a> tag leveraging some Javascript. For context, I want to have a readily available snippet that can do this on a google search in order to highlight a faux user's journey (I work for a company that sells a chatbot tool and the goal is to show how we can make the experience specific to the user if they clicked on an ad). This is strictly for demonstration purposes and would not be code I execute outside of my local machine.

I found a code block on another post (cannot seem to locate it now) and have the following:


function changeHyperlink () {

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "www.drift-demo.com"
}
}

changeHyperlink();

This works, however, all the links on the google page have a prepending href attribute of https://www.google.com so all the links now are https://www.google.com/newurl.com. My end goal is to have all the links be specific to newurl.com.

I don't know how this happening as all the href attributes (in the HTML code) are newurl.com.

Upvotes: 2

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370589

When setting the href, include the protocol, eg http or https:

const anchors = document.querySelectorAll('a');
function changeHyperlink() {
  for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "https://www.drift-demo.com";
  }
}

changeHyperlink();
<a>some anchor</a>

Upvotes: 1

Related Questions