I have N buttons on the page, and I need to find which button is clicked. So far I have this code, which will show the number of buttons, instead of button order:
Fiddle
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
console.log('You clicked element #' + );
});
}
I have N buttons on the page, and I need to find which button is clicked. So far I have this code, which will show the number of buttons, instead of button order:
Fiddle
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
console.log('You clicked element #' + );
});
}
Share
Improve this question
edited Mar 28, 2017 at 17:00
Sasha
asked Mar 28, 2017 at 16:51
SashaSasha
8,72524 gold badges98 silver badges181 bronze badges
4
- console.log('You clicked element #' + node[i]); this should work i believe – red security Commented Mar 28, 2017 at 16:53
- No that wont work, @redsecurity – trincot Commented Mar 28, 2017 at 16:54
- Oh sorry just put i not node[i] – red security Commented Mar 28, 2017 at 16:54
- That wont work either, @redsecurity – trincot Commented Mar 28, 2017 at 16:56
3 Answers
Reset to default 3You need to create a closure or use bind
, since the value of i
will have already reached the final value before you actually click and before the click handler looks up the value of i
:
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function(i) {
console.log('You clicked element #' + i);
}.bind(null, i));
}
bind
will create a copy of the function that has the current value of i
bound to it, so it does no harm if i
changes by the next iteration.
I don't now if I understand your question, but is this resolve your question?
var nodes = document.getElementsByTagName('button');
for (var i = 0, size = nodes.length; i < size; i++) {
nodes[i].addEventListener('click', function(i) {
console.log('You clicked element index' + i);
}.bind(null, i));
}
jsbin: https://jsbin./podicumeha/1/edit?html,console,output
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function(index) {
console.log('You clicked element index' + index);
}.bind(this, i));
}