Change this:
links[i].setAttribute('class', 'selected');
to this:
this.setAttribute('class', 'selected');
or better, to this:
this.className = "selected";
There's no block scope in JavaScript, so your i was stuck at the last value after the iteration.
But since all you need is a reference to the element with the handler, it's already accesssible via this inside the handler.
If you do actually need i, then you need to scope i in a new variable scope per iteration.
var links = document.getElementById('subMenu').getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
links[i].onclick = makeHandler(i);
}
function makeHandler(i) {
return function() {
links[i].setAttribute('class', 'selected');
}
}
Or just add it as a property to the DOM element.