user2347768 user2347768 - 2 months ago 8
Javascript Question

How can I removeAttribute on an array of elements?

I want when i click a link, all the classes "selected" will be removed only the clicked link will be attributed the class selected

window.onload = function() {
var link = document.getElementById('subMenu').getElementsByTagName('a');

for(var i = 0; i < link.length; i++) {
link[i].onclick = function() {
link.removeAttribute('class');
this.setAttribute('class', 'selected');
}
}
}


Firebug:

TypeError: link.removeAttribute is not a function
link.removeAttribute('class');

Ian Ian
Answer

link is the collection you got from .getElementsByTagName('a'), and doesn't have a removeAttribute method. To refer to the specific item in the loop, you should use:

this.removeAttribute("class");

Since you already understand the concept of looping through the collection and modifying each item in the collection, and are using this for setAttribute(), you should continue using this to refer to the current item in the collection that you're modifying.

The value of this in an event handler refers to the element that the event is bound to, which is what you seem to want to modify (and are already modifying).

Also, I'm not exactly sure of the point of your code, since you remove the class attribute then immediately re-set it. If you really need to set the attribute, there's no reason to remove it in the first place. If you just want to change/set the class, use:

this.className = "selected";

Per your edit, you might want to use:

window.onload = function() {
    var link = document.getElementById('subMenu').getElementsByTagName('a');

    for (var i = 0; i < link.length; i++) {
        link[i].onclick = linkClickHandler;
    }
};

function linkClickHandler() {
    var links = document.getElementById("subMenu").getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        if (links[i] !== this) {
            links[i].className = "";
        } else {
            links[i].className = "selected";
        }
    }
}

This binds the click handler for all the found elements. In the handler, it loops through all the original elements - it sets the class as "selected" for the clicked element, and sets the class for all others as "".

Comments