D
D
Denis2015-11-02 14:25:58
JavaScript
Denis, 2015-11-02 14:25:58

How to get the current index of an element in native JS?

Hello! In jQuery, finding out the current index of an element is not difficult, how to write a loop like this:

var buttons1 = $('button');

  buttons1.each(function(i) {
    $(this).click(function() {
      alert(i + 1);
    });
  });

but on native JS I tried to do the same and realized that I know little about the scope ... Who can help?
var buttons = document.querySelectorAll('button');


  for(var i = 0; i < buttons.length; i++) {
    var button = buttons[i];

    button.onclick = function() {
      alert(this.innerHTML +  i);
    }
  }

This is my version, but it doesn't work. In general, when you click on a button, a message is displayed with the index of this button. The jQuery option works, but not with native JS.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivanq, 2015-11-02
@den0820

var buttons = document.querySelectorAll('button');
for(var i = 0; i < buttons.length; i++) {
    (function(i) {
        var button = buttons[i];
        button.onclick = function() {
            alert(button.innerHTML + i);
        }
    })(i);
}

A
Alexey Ukolov, 2015-11-02
@alexey-m-ukolov

You need to wrap your function in a closure .
That's why .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question