0

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 #' + );

   });
}
4
  • console.log('You clicked element #' + node[i]); this should work i believe Commented Mar 28, 2017 at 16:53
  • No that wont work, @redsecurity Commented Mar 28, 2017 at 16:54
  • Oh sorry just put i not node[i] Commented Mar 28, 2017 at 16:54
  • That wont work either, @redsecurity Commented Mar 28, 2017 at 16:56

3 Answers 3

3

You 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.com/podicumeha/1/edit?html,console,output

Comments

1
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));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.