Get Values From Same Class Buttons
I have a problem with this script. I don't understand why Javascript doesn't recognize pdb[i]. let pbd=document.getElementsByClassName('pbda'); for (var i=0;i
Solution 1:
When your attached event listener actually runs, i
has become pbd.length
. So you are accessing an element which is not defined in your pbd
array.
If you want to access an element in its event handler, you can use this
.
let buttons = document.querySelectorAll(".man");
for(var i = 0 ; i < buttons.length;i++){
buttons[i].addEventListener("click",function(){
console.log(this);
console.log(i);
});
}
<buttonclass="man">A</button><buttonclass="man">B</button><buttonclass="man">C</button><buttonclass="man">D</button><buttonclass="man">E</button>
Also you could have replaced var
with let
. let is block scoped so the i
referred is the i
from that iteration.
Post a Comment for "Get Values From Same Class Buttons"