Paulo Dos Santos Paulo Dos Santos - 1 month ago 6
Javascript Question

How to alter the URL in a link with Javascript

I have the following code, but it is not working the way I thought.



var myList = document.getElementsByTagName("a");
var url = "http://www.site2.com";

for (i = 0; i < myList.length; i++) {
url = url + myList[i];
alert("the new link is " + url);
myList[i].setAttribute('href', url);
}

<a href="/link1.html">link1</a>
<a href="/link2.html">link2</a>
<a href="/link3.html">link3</a>
<a href="/link4.html">link4</a>
<a href="/link5.html">link5</a>





How to get this result:

<a href="http://www.site2.com/link1.html">link1</a>
<a href="http://www.site2.com/link2.html">link2</a>
<a href="http://www.site2.com/link3.html">link3</a>
<a href="http://www.site2.com/link4.html">link4</a>
<a href="http://www.site2.com/link5.html">link5</a>

Answer

Get the current attribute value and then append with the url string while setting attribute.

var myList = document.getElementsByTagName("a");
var url = "http://www.site2.com";

for (i = 0; i < myList.length; i++) {
  myList[i].setAttribute('href', url + myList[i].getAttribute('href'));
  //-----------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----
}
<a href="/link1.html">link1</a>
<a href="/link2.html">link2</a>
<a href="/link3.html">link3</a>
<a href="/link4.html">link4</a>
<a href="/link5.html">link5</a>