title: Adding event listener to multiple elements using for loop and passing different parameters
body: <pre><code>&lt;div id="mydiv0"&gt;&lt;/div&gt;
  &lt;div id="mydiv1"&gt;&lt;/div&gt;
  &lt;div id="mydiv2"&gt;&lt;/div&gt;
  
  
  var myArray = [
    document.getElementById("mydiv0"),
    document.getElementById("mydiv1"),
    document.getElementById("mydiv2")
  ];
  
  function myFunction(x){
    alert("my number is " + x);
  }
  
  for(var i = 0; i &lt; myArray.length; i++){
    myArray[i].addEventListener("click", function(){myFunction(i);});
  }
  </code></pre>
  
  <p>I want to attach event listener to each element in myArray. When clicked, an alert message should be displayed showing numbers 0,1 and 2 for mydiv0, mydiv1 and mydiv2 respectively. I tried using for loop as seen in the example above, but no matter which div I click on, I get "my number is 3" message. Is there a way to pass the different values of variable i as a parameter of myFunction?</p>