0

I have 6 buttons that all have the class "test". I want all of them to display their number, between 1 and 6.

My code is :

for (n=0 ; n < document.getElementsByClassName("test").length ; n++) {
    document.getElementsByClassName("test")[n].onclick = function() { console.log(n); };
}

But my console.log only display "6". What can I do (with the shortest code possible) ?

Runj
  • 185
  • 1
  • 2
  • 11

1 Answers1

0

You can use a closure inside of for loop

for (n = 0; n < document.getElementsByClassName("test").length; n++) {
  (function(i) {
    document.getElementsByClassName("test")[i].onclick = function() {
      console.log(i);
    };
  }(n))
}
<div class="test">click</div>
<div class="test">click</div>

You could alternatively use Array.from(), Array.prototype.forEach()

Array.from(document.getElementsByClassName("test"))
.forEach(function(el, i) {
  el.onclick = function() {
    console.log(i)
  }
})
<div class="test">click</div>
<div class="test">click</div>
guest271314
  • 1
  • 15
  • 104
  • 177