0

How do detect click on element with class

Hello. Can somebody tell me please how can I detect click on any element with a certain class? Here is my code: https://code.sololearn.com/WZ9XQeC9FY2w/?ref=app Yellow element has id and detecring click works fine, but the two green elements have class and I don't know how to detect a click on any if them. I would have to check it for each index in array I get from getElementsByClassName() method, but I bet there is an easier way.

21st Jun 2018, 7:18 AM
Jan Štěch
Jan Štěch - avatar
7 odpowiedzi
+ 1
var elems= document.getElementsByClassName("elem") function elemClick(){ console.log('green') } for( var i=0; i<elems.length; i++) elems[i].onclick= elemClick
21st Jun 2018, 7:26 AM
KrOW
KrOW - avatar
+ 1
elemClick its a function definition then you can place everywhere it mist be visible the other code (elems assignement and loop) go in window.onload
21st Jun 2018, 8:05 AM
KrOW
KrOW - avatar
+ 1
Give your attention to this line: greens[i].onclick = greenclick(); Here you CALL the greenclick function but you must ASSIGN function reference to it. Try: greens[i].onclick = greenclick;
21st Jun 2018, 8:35 AM
KrOW
KrOW - avatar
+ 1
Thank you very much. It finally works.
21st Jun 2018, 8:49 AM
Jan Štěch
Jan Štěch - avatar
0
Thanks, but which of that should be in window.onload function?
21st Jun 2018, 7:45 AM
Jan Štěch
Jan Štěch - avatar
21st Jun 2018, 8:20 AM
Jan Štěch
Jan Štěch - avatar
0
👍👍👍
21st Jun 2018, 8:56 AM
KrOW
KrOW - avatar