Javascript: Click Event For Same Class Name
I've the following code snippet. The issue is onclick event doesn't fire for the second label, which has the same class as the first one. Why is that? I searched online and found m
Solution 1:
label
is an array of all the elements with class text
, so label[0]
will only apply to the first element in the document. Simplest way to do it would probably be with a loop such as
for (var i = 0; i<label.length; i++){
label[i].onclick = function() {
console.log(true);
};
Solution 2:
var label = document.getElementsByClassName('text');
for (var i = 0; i<label.length; i++) {
label[i].oncllick = function () { console.log(true); };
}
Solution 3:
try this
var label = document.getElementsByClassName('text');
for (var i = 0; i < label.length; i++) {
label[i].onclick = function() {
console.log(true);
};
}
Post a Comment for "Javascript: Click Event For Same Class Name"