rkrk
rkrk

Reputation: 1

How to Change the Destination Domain Without Changing the Path in the Href of Anchor Tag with JavaScript?

I have a question about JavaScript.

How to change the href attribute value of an <a/> tag through JavaScript without changing the URL destination path

Example:

<a href="http://domain1.com/page">Link 1</a>
<a href="http://domain1.com/page2">Link 2</a>
<a href="http://domain1.com/page3">Link 3</a>

And I want to turn it into:

<a href="http://domain2.net/page">Link 1</a>
<a href="http://domain2.net/page2">Link 2</a>
<a href="http://domain2.net/page3">Link 3</a>

Thank you

Upvotes: 0

Views: 129

Answers (1)

Quentin
Quentin

Reputation: 943568

Use the URL API and seek out a polyfill for it if you need to support IE.

const a = document.querySelector("a");
const original_href = a.href;
const url = new URL(original_href);
url.host = "domain2.com";
const new_href = "" + url;
a.href = new_href;
console.log(new_href);
<a href="http://domain1.com/page">Link 1</a>

Upvotes: 1

Related Questions