1
window.onload = function() {
    var links = document.getElementById('subMenu').getElementsByTagName('a');
    for(var i = 0; i < links.length; i++) {
          links[i].onclick = function() {
              links[i].setAttribute('class', 'selected');
          }
    }
}

Firebug shows:

TypeError: link[i] is undefined
 link[i].setAttribute('class', 'selected');
0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.