19

I'm using Robert Nyman's script to get all elements with same class in document, but it doesn't work with onclick or any other event:

var photo = document.getElementsByClassName("photo_class","img",document.getElementById("photo_wrap")); 
photo.onclick = function(){alert("Finaly!");

Maybe you know how to fix it? Thanks!

Musa
  • 96,336
  • 17
  • 118
  • 137
Dmitriy Levchenko
  • 405
  • 1
  • 5
  • 11

5 Answers5

30

I guess photo is an array. If that's the case, try that:

var photo = document.getElementsByClassName(
    "photo_class","img",document.getElementById("photo_wrap")
);

for (var i=0; i < photo.length; i++) {
    photo[i].onclick = function(){
        alert("Finaly!");
    }
};
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
aretias
  • 341
  • 2
  • 3
6

Try

photo[0].onclick = function(){alert("Finaly!");};

getElementsByClass returns array

Musa
  • 96,336
  • 17
  • 118
  • 137
YardenST
  • 5,119
  • 2
  • 33
  • 54
3

Are you trying to do this, by any chance?

var photo = document.querySelector("#photo_wrap img.photo_class");
photo.onclick = function() {alert("Hello!");};
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

getElementsByClassName takes one parameter, the class name and returns a node list

If you want <img> elements within 'photo_wrap' with class name 'photo_class' to take the same event handler you could do something like this

var container = document.getElementById('photo_wrap');
var elements = container.getElementsByTagName('photo_class');
for(var x = 0; x < elements.length; x++) {
    // ignore anything which is not an <img>
    if(elements[x].nodeName != "IMG") {
       continue;
    }

    elements[x].addEventListener("click",function(){

      // do something when element is clicked
      this.style.backgroundColor = 'red'; // change element bgcolor to red

    },false);
}
lostsource
  • 21,070
  • 8
  • 66
  • 88
-4

Using jquery, you can easily target all the elements which have a specific class and assign an onclick event to it as shown below:

$(".photo_class").click(function(){
                            alert("Finally!")});

If you want to target a specific element which has an id, then you can use the below call:

$("#photo_element_id").click(function(){
                            alert("Finally!")});
Rups
  • 629
  • 1
  • 8
  • 19