Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByClassName onclick issue [duplicate]

Tags:

javascript

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!

like image 769
Dmitriy Levchenko Avatar asked Dec 02 '12 08:12

Dmitriy Levchenko


People also ask

What does getElementsByClassName () function return?

Document.getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

Does getElementsByClassName return in order?

getElementsByClassName("a") will reliably list them in order: d1, d2, d3, d4, d5.

In what format does the getElementsByClassName () method return its values?

The getElementsByClassName() method returns an HTMLCollection.

Is getElementsByClassName an array?

The getElementsByClassName() method returns an array-like of objects of the child elements with a specified class name. The getElementsByClassName() method is available on the document element or any other elements. The method returns the elements which is a live HTMLCollection of the matches elements.


2 Answers

I guess photo is a 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!");
    }
};
like image 60
aretias Avatar answered Sep 19 '22 15:09

aretias


Try

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

getElementsByClass returns array

like image 25
YardenST Avatar answered Sep 18 '22 15:09

YardenST