0

I am currently studying javascript so if my question is really stupid please excuse me in advance. The main idea behind this function is to take the value of the div on which the user has clicked. However, I am not sure why but no matter which class you click it takes the value of the last div. If someone can explain what I am doing wrong I will be extremely grateful.

Best regards, George

var Get_Class = document.getElementsByClassName("Letter");

for (i = 0; i < Get_Class.length; i++){
    var Letter = Get_Class[i];
   Letter.onclick = function(){
      console.log(Letter.innerHTML);
    }
}
<div class="Letter">A</div>
<div class="Letter">B</div>
<div class="Letter">C</div>
<div class="Letter">D</div>
<div class="Letter">E</div>
George Smith
  • 415
  • 8
  • 25

2 Answers2

2

Unless you want to use a closure, so i is not at the end of the loop by the time the click occurs, change

console.log(Letter.innerHTML);

to

console.log(this.innerHTML);
StackSlave
  • 10,613
  • 2
  • 18
  • 35
1

Wrap loop body with IIFE Immediately Invokable Function Expression to create distinct scope.

var Get_Class = document.getElementsByClassName("Letter");

for (var i = 0; i < Get_Class.length; i++){
  (function(j){var Letter = Get_Class[j];
    Letter.onclick = function(){
    console.log(Letter.innerHTML);
   }
  })(i);
}
<div class="Letter">A</div>
<div class="Letter">B</div>
<div class="Letter">C</div>
<div class="Letter">D</div>
<div class="Letter">E</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • A good answer should explain why the OP has their issue and how your answer fixes it. This is a duplicate that has been well covered in answers to other questions. – RobG Apr 20 '17 at 02:09