1

I know how to handle a link with an id:

var a = document.getElementById("mylink");
a.onclick = function() {
  alert("ok");
};

But if I have 3 links within one class .lotsOfLinks and I want to handle each one just like I did with Id.

What's the best and short way?

Thank you.

5 Answers5

4

Do it like this:

var elements = document.getElementsByClassName("lotsOfLinks");
for (var i = 0; i < elements.length; i++) {
    elements[i].onclick = function() {
        alert("ok");
    };
}
Andy
  • 3,997
  • 2
  • 19
  • 39
1
// use querySelectorAll for greater browser compatibility
var a = document.querySelectorAll(".mylink");

// make your handler
var handler = function() {
  alert("ok");
};

// iterate the collection, and assign the handler
for (var i = 0; i < a.length; i++) {
    a[i].onclick = handler;
}

Note that querySelectorAll doesn't work in IE6/7, but I would imagine you're not supporting those JavaScript environments at this point.

0
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++){
    if (a[i].className == "lotsOfLinks"){
        a[i].onclick = function(){ alert("ok"); }
    }
}
razz
  • 9,770
  • 7
  • 50
  • 68
  • Don't use a `for-in` loop like that. It causes problems on array-like structures, especially DOM collections. Your original loop was better, though for that type of collection, the `.length` should be cached. –  Apr 05 '13 at 16:15
  • i use `for-in` usually on those kind of arrays only when i'm querying against an attribute, i realize that this kind of arrays has one extra item at the end (i'm not sure what is it for though) and it would cause problems when the loop reachs the end of the array if i'm querying against elements, but i think it should be fine in this example? – razz Apr 05 '13 at 16:26
  • 1
    It won't hurt here, but if there comes a time where the indexed order is important, there could be issues. The extra property it's hitting is the `.length`. Sometimes there are methods as well. Overall, the `for-in` should be avoided for ordered lists. It causes too many potential problems, and gives no real benefit. Even though there's no issue here, other will people see it and therefore use it, unaware of the potential problems. –  Apr 05 '13 at 16:45
  • I agree that other people might misuse it so changed it back to normal `for` loop. thanks for explaining the `.length` property. – razz Apr 05 '13 at 17:02
0

You can try document.getElementsByClassName('myClass'); but it's not supported in IE versions prior to 9 without a polyfill

http://caniuse.com/getelementsbyclassname

Kevin Collins
  • 1,453
  • 1
  • 10
  • 16
0
  var elements = document.getElementsByClassName("lotsOfLinks");
  for(var i = 0; i < elements.length; i++) {
     elements[i].addEventListener("click", function() {
         alert("ok");
     }
  }

used the addEventListener() function.

RestingRobot
  • 2,938
  • 1
  • 23
  • 36