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.
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
+ 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
+ 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;
+ 1
Thank you very much. It finally works.
0
Thanks, but which of that should be in window.onload function?
0
ok,so why doesn't it work?
https://code.sololearn.com/WZ9XQeC9FY2w/?ref=app
0
👍👍👍