1

I have next code, but it's don't work:

<html>
<head>
    <title>Title</title>
</head>

<body>
<script type='text/javascript'>
window.onload = function(){
 var links = document.getElementsByTagName('A');
    for(var i = 0; i < links.length; i++){
        links[i].href = 'test.html';
   }
}
</script> 
<ul>
<li><a href = 1.html>1.</a></li>
<li><a href = 2.html>2.</a></li>
<li><a href = 3.html>3.</a></li>
</ul>
</body>
</html>

I need to change ALL links, on 'test.html'. Without JQuery.

Okadzaki Tomoe
  • 173
  • 2
  • 12

1 Answers1

0

You just have to change this links[i].href += 'test.html'; to the following:

 links[i].setAttrtibute('href','test.html');

Update

As Mouser have already pointed out below in his comment, this <a href = 1.html>1.</a> is not a valid HTML. You have to enclose the value you assign to the href in either single or double quotes, like below:

<a href = "1.html">1.</a>
Christos
  • 50,311
  • 8
  • 62
  • 97
  • `links[i].href = 'test.html'` should also work perfectly though? The HTML isn't valid though. `href = 1.html` should be `href="1.html"`. – Mouser Jan 31 '15 at 20:52
  • `setAttrtibute` won't work. Both `setAttribute` and `href` property should work. But changing the property is usually prefered than changing the attribute. – Oriol Jan 31 '15 at 20:54
  • @Mouser Yes. That's actually the correct way. This is related to the old [property vs attribute](http://stackoverflow.com/questions/19246714/html-attributes-vs-properties) issue. – undefined Jan 31 '15 at 20:54
  • @Vohuman thanks for the link. I wasn't aware of this. However, there is one thing I can't get. Isn't the `href` of an anchor an attribute of this element? Thanks – Christos Jan 31 '15 at 21:05
  • @Christos You are welcome. Yes, `href` is an attribute. It's used by the DOM for setting of the element's `href` property on page load. From now on JavaScript should manipulate the properties not attributes. `setAttribute` might work, but it's implementation-specific, it's safer to manipulates the properties directly instead of leaving it to the browser. – undefined Jan 31 '15 at 21:22